A very important aspect in every programming language is the mechanism that helps you manage error situations in your application. The Java programming language, as almost all modern programming languages, implements an exception-based mechanism to manage error situations. These exceptions are thrown by Java classes when an error situation is detected. You can also use these exceptions or implement your own exceptions to manage the errors produced in your classes.
Java also provides a mechanism to capture and process these exceptions. There are exceptions that must be captured or re-thrown using the throws clause of a method. These exceptions are called checked exceptions. There are exceptions that don't have to be specified or caught. These are unchecked exceptions:
- Checked exceptions: These must be specified in the throws clause of a method or caught inside them, for example, IOException or ClassNotFoundException.
- Unchecked exceptions: These don't need to be specified or caught, for example, NumberFormatException.
When a checked exception is thrown inside the run() method of a thread object, we have to catch and treat them because the run() method doesn't accept a throws clause. When an unchecked exception is thrown inside the run() method of a thread object, the default behavior is to write the stack trace in the console and exit the program.
Fortunately, Java provides us with a mechanism to catch and treat unchecked exceptions thrown in a thread object to avoid ending the program.
In this recipe, we will learn this mechanism using an example.