Uttar Pradesh, India
Instagram

try with multiple catch in java

In prior to Java 7, we have written individual catch blocks for each exception thrown by try block and the corresponding catch block structure looks like the below format.

try{

Statment 1
Statement 2
Statement 3
Statement 4

}
catch(ExceptionType1 name){
}
catch(ExceptionType2 name){
}
catch(ExceptionType3 name){
}


The execution of catch block follows certain rules

1-catch block executes child class exception first than second parent class exception the below demo program describes the following rules clearly


Demo Example:


package com.navneet.javatutorial;

public class MultipleCatchBlock {

public static void main(String[] args) {

try
{
System.out.println(10/0);

}
catch(ArithmeticException e)
{
System.out.println("Child Exception catch block");
}
catch(Exception e)
{
System.out.println("Parent Exception catch block");
}
System.out.println("Last Statement);
}
}

Another demo program for multiple exception handling by multiple catch block

package com.navneet.javatutorial;

import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class MultipleCatchBlock {

public static void main(String[] args) {

try {
System.out.println(10 / 0);
PrintWriter pw=new PrintWriter("Abc.txt");
pw.println("Demo ");
int [] array=new int[2];
array[0]=0;
array[1]=1;
array[2]=2;
for(int i=0;i<=array.length;i++){
System.out.println(array[i]);
}

} catch (ArithmeticException e) {
System.out.println("Handling code for ArithmeticException occurs");
}
catch(FileNotFoundException ex){
System.out.println("Handling code for FileNotFoundException exception occurs");
}
catch(ArrayIndexOutOfBoundsException ex){
System.out.println("Handling code for ArrayIndexOutOfBoundsException occurs");
}
finally {
System.out.println("Last Statement");
}
}
}

In  Java 7 &  later version, we have write single catch block for each exceptions thrown by try block and the corresponding catch block structure looks like the below format.The modified catch block structure are given below.

try{

Statment 1
Statement 2
Statement 3
Statement 4

}
catch(ExceptionType1 |ExceptionType2 | ExceptionType3??n name){

Handling code
}

Demo example based on the above discussion

package com.navneet.javatutorial;

import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class MultipleCatchBlock {

public static void main(String[] args) {

try {
System.out.println(10 / 0);
PrintWriter pw=new PrintWriter("Abc.txt");
pw.println("Demo");
int [] array=new int[2];
array[0]=0;
array[1]=1;
array[2]=2;
for(int i=0;i<=array.length;i++){
System.out.println(array[i]);
}

}

catch (ArithmeticException|ArrayIndexOutOfBoundsException|FileNotFoundException e) {
System.out.println("Handling code for ArithmeticException occurs");
e.printStackTrace();
}

finally {
System.out.println("Last Statement");
}
}
}


Comments

Share your thoughts in the comments

Your email address will not be published. Required fields are marked *