java - Try-catch 短路/失败 java

标签 java exception

我想使用 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/

相关文章:

java - 未找到带有 URI 调度程序错误的 HTTP 请求的映射

java - 我如何获得天花板号码(等: 5 to 10)

php - jQuery AJAX 请求因 PHP 异常而失败

delphi - 设置未处理异常过滤器 : Continue execution 1 opcode further

json - Jersey 无法捕获任何 jackson 异常

java - 类型不匹配 : cannot convert from Optional<Object> to BasketDTO

java - 如何使用 Java 和 SAX 解析带有偶尔 XML 标记的纯文本文件?

java - 为什么我写mvn help :effective-pom in the command prompt?时出现错误 "No plugin found for prefix ' help' in the current project"

Java 7 精确重抛和遗留代码

delphi - W1035 : Return value of function 'Take' might be undefined