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.
Consider the following code snippet:
public static void main(String[] args) throws FileNotFoundException
Which of the following statements about this code is correct?
FileNotFoundException
.FileNotFoundException
occurs.I had chosen the second option.
The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
An exception is thrown for one of three reasons: An abnormal execution condition was synchronously detected by the Java virtual machine. Such conditions arise because: evaluation of an expression violates the normal semantics of the language, such as an integer divide by zero, as summarized in §15.6.
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
Answer is number 4,
4.- The main method should simply terminate if any exception occurs.
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.
Check this test:
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"); } }
As you can see, if I throw a RuntimeException
the method will terminate even if the exception thrown is not a FileNotFoundException
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With