Java Catch Block
2. Catch statement
Catch block is responsible for handling an exception which is generated in the try block. It also contains multiple statements to take corrective action on the exception.
Every try block must have atleast 1 catch block, otherwise compiler gives an error.
We can write any number of catch blocks to match the particular exception based on the type of error.
Syntax
try
{
// statements that generates an exception
....
....
....
}
catch (Exception-type1 object1)
{
// Code for solving the Exception-type1
....
....
}
catch(Exception-type2 object2)
{
// Code for solving the Exception-type2
....
....
}
.
.
catch(Exception-typeN objectN)
{
// Code for solving the Exception-typeN
....
....
}
How particular catch block is executed?
- When exception is found in the try block then compiler searches for the matching catch block by passing reference of object of type generated Exception.
- Catch block is same as normal function which accepts an argument and stores into the exception object.
- If the matching catch block is found then catch block is executed and further code is continued to execution.
Example
try
{
int a=25, b=0;
int c = a/b; // generates an exception as Divided by zero.
System.out.println("Division is : "+c); // executed if there is no Exception.
}
catch(ArithmeticException AE)
{
System.out.println("Divided by zero error\nPlease change inputs");
// take action if error occurred. But never goes to try block.
}