我试图在导入文件后使用try catch语句并在catch下继续获取和错误(FileNOtFoundException e)它告诉我,异常永远不会从try语句体中抛出并将其从正文中删除。
//import scanner needed for input dialog
import java.util.Scanner;
import java.io.*;
import java.util.InputMismatchException;
import java.text.NumberFormat;
public class Lab5{
public static void main(String[]args) throws FileNotFoundException{
NumberFormat fmtCurr = NumberFormat.getCurrencyInstance();
Scanner kb = new Scanner(System.in);
//Get the filename
String fileName = null;
File inputFile = new File(fileName);
Scanner file = new Scanner(inputFile);
boolean invalid;
do{
System.out.print("Data file of prior internet usage: ")
try{
double avg;
double paid;
double total;
System.out.println("Usage history:");
while (file.hasNextLine()){
avg = file.nextDouble();
paid = file.nextDouble();
total = file.nextDouble();
System.out.println( "Average Hours Used:" + avg);
System.out.println( "Average Paid:" + fmtCurr.format(paid));
System.out.println( "Total Paid:" + fmtCurr.format(total));
}
invalid = false;
}
catch(FileNotFoundException e)
{
System.out.print("file does not exist");
invalid = true;
}
}
while(invalid = true);
}
}
答案 0 :(得分:0)
try
块必须包含可能引发异常的行,在这种情况下是Scanner file = new Scanner(inputFile);
行。如果你在try
块中移动该行,那么它将捕获异常(如果它被抛出)。
答案 1 :(得分:0)
它告诉我异常永远不会从try语句体中抛出......
是的,它告诉你确切的问题。 java.io.FileNotFoundException
块中的任何代码行都不会引发try
。
根据您的代码所做的事情,您似乎想要抓住java.util.InputMismatchException
。
catch (InputMismatchException e) // not FileNotFoundException
{
System.out.print("Invalid double input");
invalid = true;
}