Will a java exception terminate the whole java application?

后端 未结 5 2037
闹比i
闹比i 2021-02-04 10:19

I used to think that when an exception happened, the whole java application will be terminated. For example, I write a test function to test my idea.

public void         


        
5条回答
  •  -上瘾入骨i
    2021-02-04 10:37

    So, my question is, in what condition, a exception will cause the whole application to be terminated?

    See docs for details on Exceptions. As for your problem FileNotFoundException is a checked Exception which means you need to handle it. Now you have to options

    1. Catch the FileNotFoundException and handle(you can simply print stack trace and proceed)
    2. or you can throw it to the parent(calling method)

    In case 1 your java process will continue till it reaches the end(assuming no runtime Exceptions/errors occur).

    In case 2 if you do not catch your FileNotFoundException even in the parent(calling function) and just throw it again and continue to do so, the exception will finally land up in the main() method. If even your main() method throws this exception JVM will simply shut down.

    Update for clarifying your comments:

    Catching an Exception is independent of whether Excpetion is catched ot not. Inc ase of uncahed Exception you can still catch it and let the program proceed. But that is not recommended because by definition of uncached Exception(which should not happen at all) you are not suppose to recover if uncached Exception occurs.

    Consider following simple example

    public static void main(String args[]) {
        try {
            String s = null;
            System.out.println(s.length());
        } catch (Exception e) {
            System.out.println("Catch runtime exception but not quite sure what to do with it");
        }
    
        System.out.println("Reached here even after uncatched Exception");
    }
    

    output is

    Catch runtime exception but not quite sure what to do with it
    Reached here even after uncatched Exception
    

    So basically whenever Exception occurs if you do not catch it at any level from the point of origin, it will eventually propagate to main() and JVM will eventually shut down. If you do catch it(irrespective of catched or uncatched Exception) your program will proceed(output may not be as expected in case of uncatched Exceptions) and terminate.

提交回复
热议问题