Java 试着抓住短路/掉下爪哇
我想使用try-catch块来处理两种情况:一种是特定异常,另一种是任何其他异常。我能做这个吗?(举例)Java 试着抓住短路/掉下爪哇,java,exception,Java,Exception,我想使用try-catch块来处理两种情况:一种是特定异常,另一种是任何其他异常。我能做这个吗?(举例) NumberFormatException是否也由底部块处理?如果抛出NumberFormatException,它将被第一个catch捕获,第二个catch将不执行。所有其他异常都转到第二个。否,因为更具体的异常(NumberFormatException)将在第一个捕获中处理。重要的是要注意,如果交换缓存,将出现编译错误,因为必须在更一般的异常之前指定更具体的异常 这不是您的情况,但由于
NumberFormatException是否也由底部块处理?如果抛出
NumberFormatException
,它将被第一个catch
捕获,第二个catch
将不执行。所有其他异常都转到第二个。否,因为更具体的异常(NumberFormatException)将在第一个捕获中处理。重要的是要注意,如果交换缓存,将出现编译错误,因为必须在更一般的异常之前指定更具体的异常
这不是您的情况,但由于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
}
尝试以下操作:在NFEcatch中添加
抛出新异常()
try{
Integer.parseInt(args[1])
}
catch (NumberFormatException e){
// Catch a number format exception and handle the argument as a string
throw new Exception();
}
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
}
通过这种方式,您可以在其catch块中处理NFE。其他的都在另一个街区。您不需要在第二个区块再次处理NFE。是的,我可以,但我希望这对其他人也有用。另外,davidbuzatto的加入揭示了一个我不知道的特性,所以我通过问这个问题比通过简单的测试获得了更多。这不可编译。抛出的异常在原始try-catch之外,需要单独处理。
try{
Integer.parseInt(args[1])
}
catch (NumberFormatException e){
// Catch a number format exception and handle the argument as a string
throw new Exception();
}
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
}