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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)