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

后端 未结 8 1375
轮回少年
轮回少年 2021-01-01 09:31

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 a

8条回答
  •  悲&欢浪女
    2021-01-01 10:11

    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

提交回复
热议问题