我想使用 try-catch block 来处理两种情况:特定异常和任何其他异常。我可以这样做吗? (一个例子)
try{
Integer.parseInt(args[1])
}
catch (NumberFormatException e){
// Catch a number format exception and handle the argument as a string
}
catch (Exception e){
// Catch all other exceptions and do something else. In this case
// we may get an IndexOutOfBoundsException.
// We specifically don't want to handle NumberFormatException here
}
NumberFormatException 是否也会由底部 block 处理?
最佳答案
不,因为更具体的异常(NumberFormatException)将在第一个 catch 中处理。重要的是要注意,如果你交换缓存,你会得到一个编译错误,因为你必须在更一般的异常之前指定更具体的异常。
这不是你的情况,但从 Java 7 开始,你可以像这样在 catch 中对异常进行分组:
try {
// code that can throw exceptions...
} catch ( Exception1 | Exception2 | ExceptionN exc ) {
// you can handle Exception1, 2 and N in the same way here
} catch ( Exception exc ) {
// here you handle the rest
}
关于java - Try-catch 短路/失败 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11533261/