无法有效地使用Java中的Multi Catch

我真的想使用Java-1.7的function。 其中一个function是“Multi-Catch”。 目前我有以下代码

try { int Id = Integer.parseInt(idstr); TypeInfo tempTypeInfo = getTypeInfo(String.valueOf(Id)); updateTotalCount(tempTypeInfo); } catch (NumberFormatException numExcp) { numExcp.printStackTrace(); } catch (Exception exception) { exception.printStackTrace(); } 

我想从上面的代码中删除两个catch块,而是使用如下所示的单个catch:

 try { int Id = Integer.parseInt(idstr); TypeInfo tempTypeInfo = getTypeInfo(String.valueOf(Id)); updateTotalCount(tempTypeInfo); } catch (Exception | NumberFormatException ex) { // --> compile time error ex.printStackTrace(); } 

但上面的代码给出了编译时错误:

“NumberFormatException”已被替代Exception捕获。

我理解上面的编译时错误但是我的第一个代码块的替换是什么。

NumberFormatExceptionException的子类。 说两个catch块应该具有相同的行为就像是说你没有对NumberFormatException有任何特殊处理,就像你对Exception一样的一般处理。 在这种情况下,您可以省略其catch块并仅catch Exception

 try { int Id = Integer.parseInt(idstr); TypeInfo tempTypeInfo = getTypeInfo(String.valueOf(Id)); updateTotalCount(tempTypeInfo); } catch (Exception exception) { exception.printStackTrace(); } 

编译器告诉你

 } catch (Exception ex) { 

还会捕获NumberFormatExceptionexception,因为java.lang.NumberFormatException扩展了java.lang.IllegalArgumentException ,它扩展了java.lang.RuntimeException ,最终扩展了java.lang.Exception

multi-catch中的类型必须是不相交的, java.lang.NumberFormatExceptionjava.lang.NumberFormatException的子类。

您可以使用

  try { int Id = Integer.parseInt(idstr); TypeInfo tempTypeInfo = getTypeInfo(String.valueOf(Id)); updateTotalCount(tempTypeInfo); } catch (Exception exception) { exception.printStackTrace(); } 

在这种情况下,不需要multi-catch,因为NumberFormatException是从Exception派生的。 您只需捕获Exception即可获取它们。 如果您需要对NumberFormatException其他处理而不是其他exception,则必须使用您首先发布的示例。

Exception是所有exception的父类,理想情况下(首选方法 – 最佳编码实践),除非你不确定在try块中运行时会抛出什么,否则你永远不应该捕获Exception

因为,在您的代码中,您正在进行NumberFormat操作,这是Exception的子类,您不应该捕获Exception(除非其他2个方法可能抛出未经检查的exception),而是使用:

 try { int Id = Integer.parseInt(idstr); TypeInfo tempTypeInfo = getTypeInfo(String.valueOf(Id));\ updateTotalCount(tempTypeInfo); } catch (NumberFormatException npe) { npe.printStackTrace(); } 

要添加到Mureinik的解决方案:

如果您想区分每个子类的error handling,可以在catch块中使用instanceof ,例如:

 FileNotFoundException is subclass of IOException catch (IOException e) { if (e instanceof FileNotFoundException) { System.out.println("FileNotFoundException"); } else if(e instanceof IOException) { System.out.println("IOException"); } }