【问题标题】:How to know what to catch with Try/Catch Block如何知道使用 Try/Catch 块捕获什么
【发布时间】: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.ExceptionaddGrade() 和/或Grade 的构造函数被声明为抛出Exception。在 Java 中,您必须检查的异常是方法签名的一部分,并将在方法声明的 throws 子句中声明。
  • 尝试使用一个catch 子句和Exception e 作为参数
  • @SamTebbs33 这行得通,但不是一个好主意;相反,OP 应该做的是在其他子句之后添加一个 catch 子句和 Exception e 。一个更好的想法是让 OP 修改抛出 Exception 的构造函数或方法,以便它改为抛出其子类之一。

标签: java try-catch


【解决方案1】:

我假设 Grade.addGrade 方法或 Grade 构造函数被声明为抛出 java.lang.Exception

在使用 Integer.parse 方法时捕获 java.lang.NumberFormatException 也是一个好习惯。

【讨论】:

  • 谢谢!这就是问题所在!我以为它们是可以互换的。你能解释一下到底有什么区别吗?感谢NumberFormatException 的提示,我一定会把它添加到我的代码中。
  • Exception 是一个基类,IOException 扩展了 Exception,FileNotFoundException 扩展了 IOException。通过捕获基类,您也可以捕获所有派生类,但反过来就不行了。你可以在这里找到更多信息:docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html
【解决方案2】:

答案:

首先,如果您想知道捕获什么(或者更好地说,抛出什么),您首先需要查看 Java 文档。这向您显示了每个官方支持的类的每个方法的详细大纲,因此您最好在执行输入/输出等敏感操作之前查看它。

因此,我建议您在现有语句的末尾添加一个额外的 catch 块,并使其捕获 java.lang.Exception,也就是众所周知的 主异常,来自所有其他异常都源自和扩展。

这不是解决问题的最理想的方法,但它不会像在多 if 语句的末尾放置 else 语句那么重要,因为您只是提供了一个后备在所有其他块失败的情况下阻止。这只是恰好满足编译器的额外保护层。

代码演示

这只是演示代码,只是为了说明应该做什么。因为我不知道你的项目是什么,和/或你在做什么,我只会展示你需要做什么的准系统,并且以我知道的方式,我可以对由此直接或间接导致的任何事情负责最终产品中使用的代码。

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;
 }catch(Exception e){
     e.printStackTrace();
     //...OTHER HANDLING CODE. THE ABOVE COULD BE LEFT BLANK...//
 }//load

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 2021-05-13
    • 2010-09-07
    • 1970-01-01
    • 2016-05-29
    • 2011-10-06
    • 2021-10-08
    相关资源
    最近更新 更多