我正在复习我为明天早上的期末考试做的期中考试。这个问题我答错了,但没有指出正确的答案,我忽略了问教授。
考虑以下代码片段:
public static void main(String[] args) throws FileNotFoundException
以下关于这段代码的说法正确的是?
- main 方法旨在捕获和处理所有类型的异常。
- main方法旨在捕获和处理
FileNotFoundException
。 - 如果
FileNotFoundException
发生,主方法应该简单地终止。 - 如果发生任何异常,主方法应该简单地终止。
我选择了第二个选项。
最佳答案
答案是4,
4.- The main method should simply terminate if any exception occurs.
throws 子句仅声明该方法抛出一个检查过的 FileNotFoundException 并且调用方法应该捕获或重新抛出它。如果在 main 方法中抛出(而不是捕获)未经检查的异常,它也会终止。
检查这个测试:
public class ExceptionThrownTest {
@Test
public void testingExceptions() {
try {
ExceptionThrownTest.main(new String[] {});
} catch (Throwable e) {
assertTrue(e instanceof RuntimeException);
}
}
public static void main(String[] args) throws FileNotFoundException {
dangerousMethod();
// Won't be executed because RuntimeException thrown
unreachableMethod();
}
private static void dangerousMethod() {
throw new RuntimeException();
}
private static void unreachableMethod() {
System.out.println("Won't execute");
}
}
如您所见,如果我抛出 RuntimeException
,即使抛出的异常不是 FileNotFoundException
关于java - main方法抛出异常是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13773340/