【发布时间】:2015-02-22 02:12:32
【问题描述】:
我只是想用 BufferedReader 读入一个文本文件,我正在使用一个 try-catch 块,它应该可以捕获任何 IOExceptions。我认为确实如此,甚至添加了FileNotFoundException,以防出现问题。但我仍然得到:
错误: 未报告的异常 java.lang.Exception;必须被抓住或宣布被扔掉
而且我不明白我没有抓住哪一部分。这是我的代码:
public Grade load(){
Grade newList = new Grade();
try {
int year;
String newLine;
BufferedReader inFile = new BufferedReader(new FileReader(inputName));
while((newLine = inFile.readLine())!= null){
year = Integer.parseInt(inFile.readLine());
newList.addGrade(new Grade(year));
}
inFile.close();
}//try
catch (FileNotFoundException e) {
System.out.println("Failed to copy the file: "+e.getMessage());}
catch(IOException e){
System.out.println("Failed to copy the file: "+e.getMessage());}
return newList;
}//load
【问题讨论】:
-
newList是什么,addGrade()抛出什么? -
而且您应该使用
try-with-resources来确保BufferedReader无论结果如何都已关闭 -
还有
new Grade(year)可能是异常源。由于编译器明确提及java.lang.Exception,addGrade()和/或Grade的构造函数被声明为抛出Exception。在 Java 中,您必须检查的异常是方法签名的一部分,并将在方法声明的throws子句中声明。 -
尝试使用一个
catch子句和Exception e作为参数 -
@SamTebbs33 这行得通,但不是一个好主意;相反,OP 应该做的是在其他子句之后添加一个
catch子句和Exception e。一个更好的想法是让 OP 修改抛出Exception的构造函数或方法,以便它改为抛出其子类之一。