Handling Exception in Java
Sesha-Savanth
Posted on October 24, 2021
What is exception handling?
An exception is an abnormal condition that disturbs the normal flow of the program. Exception handling is used in handling the runtime errors and maintains the continuity of the program.
Java exceptions
- Checked
- Unchecked
- Errors
Try Block
The statements which throw an exception are to be placed under try block
It is suggested not to write unnecessary statements in the try block because the program terminates at a particular statement where an exception occurs.
Catch Block
It is used to handle the exception by declaring the type of exception within the parameter.
Single or multiple catch blocks can be used after each single try block.
Syntax of try-catch :'
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Program using Try-Catch :
public class TryCatch {
public static void main(String[] args) {
try
{
int arr[]= {2,4,6,8};
System.out.println(arr[10]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("Program continues");
}
}
Output
java.lang.ArrayIndexOutOfBoundsException: 10
Program continues
Program Using multiple catch blocks :
public class Multiple {
public static void main(String[] args) {
try{
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("Program Continues");
}
}
Output
ArrayIndexOutOfBounds Exception occurs
Program Continues
Finally Block
The block of statements that are used to execute the important code. It is always executed whether an exception is handled or not.
Program using finally block :
public class Finally{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){
System.out.println(e);
}
finally{
System.out.println("finally block is always executed");
}
System.out.println("Program continues");
}
}
Output
java.lang.ArithmeticException: / by zero
finally block is always executed
Program continues
Posted on October 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 27, 2024