In Java the way of handling the exceptions varies from exception to exception, hence for every exception type it is highly recommended to use a separate catch block i.e., try with multiple catch blocks.
For Example-
try{
// Risky code
}
catch(ArithmeticException e)
{
// Alternative Airthmetic logic
}
catch(FileNotFoundException e)
{
// Alternative logic for fle
}
While working with multiple catch blocks, the order of catch blocks is very important. We have to take the child exception first after that parent exception otherwise we will get compile time error.
For Example- in the below code, we will get compile time error-“Exception ‘java.lang.ArithmeticException’ has already been caught”.
import java.io.FileNotFoundException;
public class ExceptionHandling {
public static void main(String[] args) {
try {
System.out.println(10 / 0);
}
catch (Exception e){
e.printStackTrace();
}
catch (ArithmeticException e){
e.printStackTrace();
}
}
}
- We cannot take more than one catch block for the same exception otherwise we will get compile time error.
import java.io.FileNotFoundException;
public class ExceptionHandling {
public static void main(String[] args) {
try {
System.out.println(10 / 0);
}
catch (ArithmeticException e){
e.printStackTrace();
}
catch (ArithmeticException e){
e.printStackTrace();
}
}
}
Similar Java Tutorials
- Odd Even in Java
- Fibonacci Series Java
- Switch statements in Java
- For loop in Java
- While loop in Java
- Do while loop in Java
- Import statement in Java
- Abstract modifier in Java
- Strictfp modifier in Java
- Final variable in Java
- Adapter Class in Java
- Method signature in Java
- Method overloading in Java
- Has A Relationship
- Inheritance in Java
- Encapsulation in Java
- Abstraction in Java
- Data Hiding in Java
- Interface vs abstract class
- Method Overriding in Java
- Method Overloading in Java
- Coupling in Java
- Method to print exception information in Java
- Exception Handling by Using try-catch in Java
- Checked Exception vs Unchecked Exception
- Exception Hierarchy in Java
- Java Exception Handling Interview Questions
10 thoughts on “try with multiple catch block in Java”