try{
//Block of code to monitor of Errors
}catch(ExceptionType1 exceptionObject){
//Exception Handler for ExceptionType1
}catch(ExceptionType2 exceptionObject){
//Exception Handler for ExceptionType2
}
Exception Types
All Exception types in Java are of type Throwable. Thus Throwable is at the top of Exception hierarchy. Immediately below Throwable are two subclasses that partition exception into Exception and Errors.
Errors are catastrophic failures which are usually not handled by our program. On the other hand Exceptions class is used for exceptional conditions that user program should catch. There is an important subclass of Exception i.e. Runtime Exceptions. Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing.
Why Exceptions?
Before we start looking at how to catch the Exceptions, Let's look at why there is a need of Exception Handling. Let's write a program which does not handle the exceptions.
public class NoHandling {
public static void main(String args[]) {
int d = 0;
int a = 232 / d;
}
}
On running this program will generate the following stack trace.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at info.FiveBalloons.Examples.NoHandling.main(NoHandling.java:7)
The stacktrace will show the sequence of method invocation that led up to the error. This is the default exception handling provided by the Java run-time system. But you will want to handle the exceptions yourself. Doing so provides two benefits.
1. It allows you to fix the error.
2. It prevents the program from automatically terminating.
Let's fix the above piece of code using Java Exception Handling.
public class NoHandling {
public static void main(String args[]) {
int d, a;
try {
d = 0;
a = 232 / d;
} catch (ArithmeticException e) { // Catch divide-by-zero Errors
a = 0;
System.out.println("Division by Zero, setting value of a as 0");
}
}
}
As you can see in the catch block we have adjusted the value of a, as well as handled the exception so that the code does not terminate at the exception.