简体   繁体   中英

Who and how handle the exception when we use throws?

class Test{

public static void main(String[] cv) throws IOException{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String s=br.readLine();
 }

}

When we're writing throws then who is actually handling the IOException here? Whe we use try-catch we can handle it in the catch block. But here how and who is handling?

When you have a method with a throws clause, then any other method that calls that method has to either handle the exception (by catching it) or throwing it furter by also having a throws clause for that type of exception (so that, in turn, the method that calls that one again has to do the same, etc.).

When the main method has a throws clause, then the JVM will take care of catching the exception, and by default it will just print the stack trace of the exception.

When you want to do special handling when main throws an exception, then you can set an uncaught exception handler:

Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.err.printf("Thread %s threw an uncaught exception!%n", t.getName());
        e.printStackTrace();
    }
});

Nobody is handling it there, because main is the entry point of the program.

When you use throws you are leaving to the caller of the method, the responsability to handle the exception. Here, there is no caller of the method except for the JVM itself which will handle the exception by stopping your program and printing the stack trace.

I believe JVM will handle it by stopping the main thread and printing exception stacktrace to standard output

Saying throws allows you to skip handling exceptions at that stage of the program. The best example and use of it will be:

Suppose you are creating an integer calculator which has multiple functions for add, subtract, divide etc. If you declare divide method throws DivideByZeroException, your main calculator program will have to handle it. Doing it this way, your program knows exactly what problem occured. Had it been done under function level, your main program would never know.

This approach is excellent when developing libraries since you can't include Sop statements in your library functions. In this case, it is the JVM itself that handles this Exception.

When a method declares throwing a checked exception, the caller of the method is supposed to handle them. In case of a runtime exception, the caller could handle the exception but it's not required to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM