The exception class hierarchy starts at the java.lang.Throwable class.
When an exception is thrown, it must be an object of the Throwable class, or any of its subclasses.
The parameter of the catch block must be of type Throwable, or one of its subclasses, such as Exception, ArithmeticException, IOException, etc.
We can create our own exception classes by inheriting our classes from one of the exception classes.
Java runtime selects the appropriate catch block and starts looking for the appropriate catch clock sequentially starting from the first catch block.
Multiple catch blocks for a try block must be arranged from the most specific exception type to the most generic exception type.
The following code uses a valid sequence of multiple catch blocks.
The ArithmeticException class is a subclass of the RuntimeException class.
If both of these exceptions are handled in catch blocks for the same try block, the most specific type, which is ArithmeticException, must appear before the most generic type, which is RuntimeException.
try { // Do something, which might throw Exception } catch(ArithmeticException e1) { // Handle ArithmeticException first } catch(RuntimeException e2) { // Handle RuntimeException after ArithmeticException }
There are three types of exceptions
Exceptions in the first category are known as checked exceptions because the compiler checks that they are handled in the code.
The Throwable class, the Exception class, and subclasses of the Exception class, excluding the RuntimeException class and its subclasses, are called checked exceptions.
All exceptions that are not checked exceptions are called unchecked exceptions because the compiler does not check if they are handled in the code.
The Error class, all subclasses of the Error class, the RuntimeException class, and all its subclasses are unchecked exceptions.
We can handle the unchecked exception if we want to, the compiler would not force us to do it.
The program structure for handling a checked or an unchecked exception is the same.
The following code shows how to handle a checked exception
import java.io.IOException; // w ww . ja v a2 s . c o m public class Main { public static void main(String[] argv) { try { int input = System.in.read(); if (input != -1) { System.out.println(input); } } catch (IOException e) { System.out.print("IOException occurred."); } } }