What does it mean when the main method throws an exception?

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


Dude, a little late, but answer is Number 3.

Number 1 is false because it is not handling FileNotFoundException

Number 2 is false for the same reason.

Number 3 is true. If a FileNotFoundException is thrown, the main method will terminate.

Number 4 is false. It would not terminate in case of ANY exception. It would terminate only in case of unchecked exception or FileNotFoundException. If there are not other checked exceptions declared in the 'throws' clause, it means they are being handled within the method.

Tags:

Java

Exception