Catch Multiple Exceptions In Java

Mouad Oumous
The Fresh Writes
Published in
9 min readFeb 16, 2023
Catch Multiple Exceptions In Java

To handle multiple exceptions in java we can :

  • Use Multiple Catch Blocks: Here you can handle multiple exceptions under multiple catch block for a corresponding try block. Program flow will automatically come to the catch block one by one and then, the corresponding catch block is found as per the exception and will be handled accordingly.
  • Use Multiple Catch Statements in Arguments of A Catch Block: This feature came from Java 7. Here you can handle multiple exceptions under a single catch block (separated by pipe sign) for a corresponding try block. Program flow will automatically come to the catch block and then, the corresponding exception inside the arguments of catch block is found for the try block and will be handled accordingly.

· Mutiple catch blocks
Why do we need multiple catch blocks in Java?
Syntax
Flowchart of Multi-catch Block
Examples
· Catching More Than One Type of Exception with One Exception Handler
Syntax
Examples
Catching base Exception
· Program

Mutiple catch blocks

In Java, a single try block can have multiple catch blocks.

Why do we need multiple catch blocks in Java?

Multiple catch blocks in Java are used to handle different types of exceptions. When statements in a single try block generate multiple exceptions, we require multiple catch blocks to handle different types of exceptions. This mechanism is called multi-catch block in java.

A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. You can catch different exceptions in different catch blocks if it contains a different exception handler. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. So, if you have to perform different tasks at the occurrence of different exceptions, you can use the multi-try catch in Java.

Syntax

The syntax for using a single try with more than one catch block in java is as follows:

try 
{
statements;
}
catch(ExceptionType1 e1)
{
statements;
}
catch(ExceptionType2 e2)
{
statements;
}

Java multi-catch block acts as a case in a switch statement. In the above syntax, if the exception object (ExceptionType1) is thrown by try block, the first catch block will catch the exception object thrown and the remaining catch block will be skipped.

In case, exception object thrown does not match with the first catch block, the second catch block will check, and so on.

At a time only one exception occurs and at a time only one catch block is executed. All catch blocks must be arranged in such a way that exception must come from the first subclass and then superclass, i.e. catch for ArithmeticException must come before catch for Exception.

Flowchart of Multi-catch Block

Flowchart of Multi-catch Block

Examples

Example 1

class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}

Output

/ by zero

In this example, two exceptions may occur:

  • ArithmeticException because we are trying to divide a number by 0.
  • ArrayIndexOutOfBoundException because we have declared a new integer array with array bounds 0 to 9 and we are trying to assign a value to index 10.

We are printing out the exception message in both the catch blocks i.e. duplicate code.

The associativity of the assignment operator = is right to left, so an ArithmeticException is thrown first with the message / by zero.

Example 2

class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}

Output:

Warning: ArithmeticException
Out of try-catch block...

In the above example there are multiple catch blocks and these catch blocks executes sequentially when an exception occurs in try block. Which means if you put the last catch block ( catch(Exception e)) at the first place, just after try block then in case of any exception this block will execute as it can handle all exceptions. This catch block should be placed at the last to avoid such situations.

Catching More Than One Type of Exception with One Exception Handler

In Java 7 and later, catch block has been improved to handle multiple exceptions in a single catch block. If you are catching multiple exceptions and they have similar code.

A single catch block has the posibility to to handle (catch) multiple exceptions by separating each with | (pipe symbol) in the catch block.

This feature can reduce code duplication and increases efficiency also lessen the temptation to catch an overly broad exception.. The bytecode generated while compiling this program will be smaller than the program having multiple catch blocks as there is no code redundancy.

Consider the following example, which contains duplicate code in each of the catch blocks:

catch (IOException ex) {
logger.log(ex);
ex.printStackTrace();
catch (SQLException ex) {
logger.log(ex);
ex.printStackTrace();
}

In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable ex has different types.

In Java SE 7 and later, we can eliminate the duplicated code by using this approch

Syntax

In the catch clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (|):

try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}

The pipe symbol (|) can be used to divide up a catch block that handles numerous exceptions. In this example, the exception argument (ex) is final, meaning that it cannot be changed. This feature produces less code repetition and smaller byte code.

Examples

Example 1

class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}

Output

/ by zero

Catching multiple exceptions in a single catch block reduces code duplication and increases efficiency.

The bytecode generated while compiling this program will be smaller than the program having multiple catch blocks as there is no code redundancy.

Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.

This approch usually used if you are catching multiple exceptions and they have similar code. but we can also use it as we like.

Example 2

class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException|ArrayIndexOutOfBoundsException e) {
if (e instanceof ArithmeticException)
System.out.println("ArithmeticException");
else
System.out.println("ArrayIndexOutOfBoundsException");
}
}
}

Catching base Exception

When catching multiple exceptions in a single catch block, the rule is generalized to specialized.

This means that if there is a hierarchy of exceptions in the catch block, we can catch the base exception only instead of catching multiple specialized exceptions.

Let’s take an example.

Example 1: Catching base exception class only

class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

Output

/ by zero

We know that all the exception classes are subclasses of the Exception class. So, instead of catching multiple specialized exceptions, we can simply catch the Exception class.

If the base exception class has already been specified in the catch block, do not use child exception classes in the same catch block. Otherwise, we will get a compilation error.

Let’s take an example.

Example 2: Catching base and child exception classes

class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (Exception | ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}

Output

Main.java:6: error: Alternatives in a multi-catch statement cannot be related by subclassing

In this example, ArithmeticException and ArrayIndexOutOfBoundException are both subclasses of the Exception class. So, we get a compilation error.

Program

In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block. The following example traps two different exception types:

// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}

This program will cause a division-by-zero exception if it is started with no commandline arguments, since a will equal zero. It will survive the division if you provide a command-line argument, setting a to something larger than zero. But it will cause an ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the program attempts to assign a value to c[42].

Here is the output generated by running it both ways:

C:\>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.

When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their superclasses. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its superclass. Further, in Java, unreachable code is an error. For example, consider the following program:

/* This program contains an error.
A subclass must come before its superclass in
a series of catch statements. If not,
unreachable code will be created and a
compile-time error will result.
*/
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
} catch(Exception e) {
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) { // ERROR - unreachable
System.out.println("This is never reached.");
}
}
}

If you try to compile this program, you will receive an error message stating that the second catch statement is unreachable because the exception has already been caught. Since ArithmeticException is a subclass of Exception, the first catch statement will handle all Exception-based errors, including ArithmeticException. This means that the second catch statement will never execute. To fix the problem, reverse the order of the catch statements.

Join Mouad Oumous Java WhatsApp Group JOIN

Join Mouad Oumous Telegram Channel JOIN

--

--

Mouad Oumous
The Fresh Writes

I'm a blogger on medium, l'm a java and kotlin developer, also an Android Developer I mastered various topics such as Networking, UI , UX, Animation ...