java - 为什么有些 Java 异常可以不处理?

标签 java exception

    public static void main(String[] args) {
    File file = new File("foobar"); 
    file.createNewFile();

    String baz = "baz";     
    int myInt = Integer.parseInt(baz);
}

在此代码中,IDE 或编译器会提示 createNewFile() 抛出了未处理的异常,我们需要捕获它以允许代码编译。

但是 parseInt() 也会抛出一个异常,NumberFormatException,但我们不需要捕获它,尽管这似乎是个好主意。为什么我们不需要捕获该异常?

最佳答案

规则是不需要捕获扩展 RuntimeException 的异常。

NumberFormatException 扩展了 IllegalArgumentException,后者扩展了 RuntimeException

来自Oracle documentation :

Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).

关于java - 为什么有些 Java 异常可以不处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26489786/

相关文章:

asp.net - 可能在 ASP.Net 页面中抛出 404 错误?

java - 源字符串可以转换为目标字符串吗?

java - 使用 java "no such file or directory"运行 groovy 编译类的 Bash 错误

java - 如何从 Java 中的重写方法传播异常

线程中的Java异常 "AWT-EventQueue-0"java.lang.ArrayIndexOutOfBoundsException : 1

java - ExceptionHandler,得到 java.lang.IllegalStateException : Could not resolve method parameter at index 0?

java - 线程中的方法调用给出 "Can' t 在线程内创建处理程序“异常

java - Base64解码android中的正常未编码字符串不会给出任何异常

java - Android Studio Java 模块找不到依赖项

java - 如何在Java中为正则表达式转义文本