Search code examples
javaexceptiontry-catchtry-catch-finally

Can we catch an exception without catch block?


Suppose I have a try-finally block without catch block, we throw an exception inside the try block. Am I able to catch that exception?

public static void main(String[] args) throws IOException{
    try {
        throw new IOException("Something went wrong");
    } finally{
    }
}

Solution

  • Yes, it is possible.

    You can use an uncaught exception handler. Its responsibility is to catch the exceptions that your program didn't catch, and do something with it.

    public static void main(String[] args) throws IOException {
        Thread.setDefaultUncaughtExceptionHandler((thread, thr) -> thr.printStackTrace());
        throw new IOException("Something went wrong");
    }
    

    setDefaultUncaughtExceptionHandler is a method that will register a handler that will be invoked when an exception has been thrown in any thread and wasn't caught. The above code will print the stacktrace of the throwable handled.

    The handler takes as argument the thread where the exception happened and the throwable that was thrown.

    You can also have a handler per thread by using setUncaughtExceptionHandler on a Thread instance. This handler would handle all uncaught exceptions thrown from this thread.