当main方法抛出异常时,它意味着什么? [英] What does it mean when the main method throws an exception?
问题描述
我正在审查我为明天上午的期末考试做准备的期中考试。我错了这个问题,但是没有正确的答案指出,我忽略了向教授询问它。
I'm reviewing a midterm I did in preparation for my final exam tomorrow morning. I got this question wrong, but there's no correct answer pointed out, and I neglected to ask the prof about it.
考虑以下代码片段:
public static void main(String[] args) throws FileNotFoundException
关于此代码的以下哪些陈述是正确的?
Which of the following statements about this code is correct?
- 主要方法旨在捕获处理所有类型的异常。
- main方法用于捕获和处理
FileNotFoundException
。 - 如果发生
FileNotFoundException
,主要方法应该终止。 - 如果发生任何异常,主方法应该终止。
- The main method is designed to catch and handle all types of exceptions.
- The main method is designed to catch and handle the
FileNotFoundException
. - The main method should simply terminate if the
FileNotFoundException
occurs. - The main method should simply terminate if any exception occurs.
我选择了第二个选项。
推荐答案
答案是4号,
4.-主要方法应该在发生任何异常时终止。
4.- The main method should simply terminate if any exception occurs.
throws子句仅声明该方法抛出已检查的FileNotFoundException,并且调用方法应该捕获或重新抛出它。如果在main方法中抛出(而不是catch)未检查的异常,它也将终止。
The throws clause only states that the method throws a checked FileNotFoundException and the calling method should catch or rethrow it. If a non-checked exception is thrown (and not catch) in the main method, it will also terminate.
检查此测试:
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
As you can see, if I throw a RuntimeException
the method will terminate even if the exception thrown is not a FileNotFoundException
这篇关于当main方法抛出异常时,它意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!