尝试捕获短路/直通java

dmi*_*mi_ 4 java exception

我想使用try-catch块来处理两种情况:一个特定的异常,以及任何其他异常.我可以这样做吗?(一个例子)

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      
}
Run Code Online (Sandbox Code Playgroud)

NumberFormatException是否也由底部块处理?

dav*_*tto 11

不,因为将在第一个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
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*her 5

如果 aNumberFormatException被抛出,它将被第一个捕获,catch第二个catch不会被执行。所有其他例外都属于第二个。