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

后端 未结 8 1336
轮回少年
轮回少年 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:08

    With only the declaration of main(), it is impossible to say which answer is objectively correct. Any of the statements could be true, depending on the definition of the method.

    1. The main method is designed to catch and handle all types of exceptions.

    2. The main method is designed to catch and handle the FileNotFoundException.

    Both of the above statements are true of the following:

    public static void main(String[] args) throws FileNotFoundException {
        while (true) {
            try {
                doSomething();
            }
            catch (Exception e) {}
        }
    }
    

    The declared exception is never thrown by main(), but that is not an error; just pointless and misleading.

    1. The main method should simply terminate if the FileNotFoundException occurs.

    2. The main method should simply terminate if any exception occurs.

    Both of the above statements are true of the following:

    public static void main(String[] args) throws FileNotFoundException {
        try {
            doSomething();
        }
        catch (Exception e) {
            return;
        }
    } 
    

    Of course, we can guess at the intention of the question based on what a decent and reasonable programmer might intend to communicate with this method signature. Which would be that they intend for the method to throw FileNotFoundException, and necessarily handle other checked Exceptions. We can also reasonably assume that "handle" does not just mean "process", but specifically that it will not (re-)throw such an exception.

    These assumptions immediately rule out #1 and #2.

    The remaining question is whether "simply terminate" includes throwing an exception, or only an explicit return/System.exit(). In the former case, both of #3 and #4 could still be true:

    public static void main(String[] args) throws FileNotFoundException {
        try {
            doSomething();
        }
        catch (FileNotFoundException fnfe) {
            throw fnfe;
        }
        catch (Exception e) {
            return;
        }
    }
    

    In the latter case, neither #3 nor #4 can be true while also satisfying the assumption that main() will throw FileNotFoundException.


    In sum, the options are not worded well. If I had to pick an answer, it would be #3 based on the logic of MartinV's answer. My assumption would be that the word "should" in #3 was an unfortunate choice by the professor, and that something like "may" would have been a better option. It would also have been a good idea to use more precise language than "simply terminate" (and, arguably, "handle").

提交回复
热议问题