Table of Contents
Exceptions
Exceptions are unwanted or unexpected events that inhibit the natural flow of a program. Exceptions are different from computational errors. While the natural tendency of an application is to not catch errors, it tries to catch exceptions in various forms. We use a try-catch block to catch exceptions. The snippet of code inside a try block is tested for exceptions that are caught in the catch block. It so happens several times when an exception falls through the program without getting caught. These exceptions are not picked up in the try-catch block. In such cases, the JVM prints out the exception stack and then terminates the program. In this article, we will discuss in detail how uncaught exceptions are handled.
How to Handle Uncaught Exceptions
Uncaught exceptions occur in a thread. Java follows this thread when dealing with the exceptions. In the event of an uncaught exception, JVM summons the uncaught exception handler. This is part of the UncaughtExceptionHandler interface. This interface has a handleException () method that is responsible for printing out the stack trace. Another process that involves uncaught exception handling calls the JVM which in turn calls a special function called dispatchUncaughtException() on the thread where the Exception has taken place. After handling, the thread is terminated in both cases and the program comes to a halt.
Although this is the general practice, it can be overridden using the following table:
Which Thread Handler to set | How to Set | Notes |
All | Thread.setDefaultUncaughtExceptionHandler() | Depends on the ThreadGroup’s uncaughtException(). |
All for a particular thread group | Override ThreadGroup.uncaughtException() | This will require a ThreadGroup subclass. |
Individual Thread | Thread.setUncaughtExceptionHandler() | The method getUncaughtExceptionHandler() method can be overridden provided you are using your own Thread subclass. |
To make sure your program does not abruptly crash, care should be taken such that uncaught exceptions do not terminate main threads.
0 Comments