Exception Handling in Java: try..catch..finally
Exception is an event which interrupts the normal flow of the program execution. It may occur due to some programming mistake or any unidentified errors.
Run the following code and observe the output:
class Program{
public static void main(String args[]){
int a=2;
int b = 0;
int c = a/b;
System.out.println("result is:"+c);
int d = a+b;
System.out.println("addition is :"+d);
}
}
This program throws a java.lang.ArithmeticExcption, and the execution of the program will stop.
Exception class in Java has been provided to handle exceptions:
Note: Exception class is a sub class of Throwable class.
Try catch block:
Using try catch block, we can handle multiple exceptions.
Syntax:
try{
//Code where exception occurs
}
catch(Exception1 e1){
//Handle exception 1
}
catch(Exception1 e2){
//Handle exception 2
}
Note: try catch block can have one or more catch block associated with it.
Now let's try to handle above exception using try catch block.
class Program{
public static void main(String args[]){
int a=2;
int b = 0;
try{
int c = a/b;
System.out.println("result is:"+c);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
int d = a+b;
System.out.println("addition is :"+d);
}
}
We can handle multiple exceptions at once using a single catch block as:
catch(Exception1 | Exception2 | Exception3 e){
//Handle exception
}
Here the program will handle the exception and code execution will not stop.
finally block:
With try catch block we can use finally block as well.
Syntax:
try{
//Code where exception occurs
}
catch(Exception1 e1){
//Handle exception 1
}
finally{
//always executes
}
Irrespective of the occurrence of the exception, finally block will always execute. It is often used for closing connections, release resources etc.
Example:
class Program{
public static void main(String args[]){
int a=2;
int b = 0;
try{
int c = a/b;
System.out.println("result is:"+c);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
finally{
System.out.println("Finally block");
}
int d = a+b;
System.out.println("addition is :"+d);
}
}
Execute the above code, you'll see that finally block executes even after exception occurs. Try executing the above code by changing the value of b from zero to a non-zero value. Finally code will still execute.
There are two types of exception
1. Checked Exception
2. Unchecked Exception
1. Checked Exception:
Checked exceptions are also called compile-time exception as these exceptions are detected during the compilation of the program.
Example: FileNotFoundException, IOException etc.
2. Unchecked Exception:
Unchecked exceptions are also called run-time exception as these exceptions are detected during the execution of the program.
Example: RuntimeException such as ArithmeticException, IndexOutOfBoundsException etc.
Comments
Post a Comment