Site icon TestingDocs.com

Handle Multiple Exceptions in Java

Overview

In this section, we will learn to handle multiple exceptions in java automation code. We can use multiple catch blocks to handle multiple exceptions in the code.

Sample Code

import java.io.IOException;

public class MultipleExceptions {

public static void main(String[] args) {
try {
throw new Exception("Throwing Sample Exception");
}
catch(IOException ioe) {
ioe.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}

}

}

 

Common mistake

While using multiple catch statements in automation code, it is important to remember that sub class of class Exception inside catch must come before any of their super class. IOException is a sub-class of Exception class in the class hierarchy.

import java.io.IOException;

public class MultipleExceptions {

public static void main(String[] args) {
try {
throw new Exception();
}
catch(Exception e) {
e.printStackTrace();
}
catch(IOException ioe) {
ioe.printStackTrace();

}
}

}

 

The above code would cause a compile-time error.

Compile time error:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Unreachable catch block for IOException. It is already handled by the catch block for Exception

at MultipleExceptions.main(MultipleExceptions.java:12)

Handling in a single block

Catching two or more exceptions in a single handler catch block. The following shows the usage of handling two exceptions with a single catch block.

public class MultipleExceptions {

public static void main(String[] args) {
try {
int[] a= {1,2,3};
double b= a[1]/a[2];
System.out.println(b);
}
catch(IndexOutOfBoundsException | ArithmeticException e) {
e.printStackTrace();
}

}

}

 

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version