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
。
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/