Java 7 – Multi-catch block with examples

In this article, we will discuss new feature called multi-catch block introduced in Java 1.7 version as part of Exception handling for combining different types of exception into single catch block separated by pipe character (|)

1. Until Java 1.6 version:

  • There might be possibility of throwing multiple exceptions from try-block
  • So, whenever multiple exception is thrown, then programmer has to provide multiple catch block to catch different types of exception
  • The reason to have multiple catch block is that, we can provide different exception handler code for different types of exception

1.1 Pseudo code for try with multiple catch blocks:

try {

	// code which might raise exception

}
catch(ArithmeticException aex) {

	// corresponding handling code, if any exception from try block
	aex.printStackTrace();
}
catch(NullPointerException npex) {

	// corresponding handling code, if any exception from try block
	System.out.println(npex.toString());
}
catch(NumberFormatException nfex) {

	// corresponding handling code, if any exception from try block
	System.out.println(nfex.toString());
}
catch(ArrayIndexOutOfBoundsException aioobex) {

	// corresponding handling code, if any exception from try block
	System.out.println(aioobex.toString());
}

Let us see an example for catching different types of exception using multiple catch blocks

MultipleCatchBlockForDifferentTypesOfException.java

package in.bench.resources.exception.handling;

public class MultipleCatchBlockForDifferentTypesOfException {

	public static void main(String[] args) {

		try {

			// code which might raise exception

			// arithmetic operation
			int result = 18/0;
			System.out.println("Result of division : "
					+ result);

			// String operation
			String str = null;
			System.out.println("Lenght of the String : "
					+ str.length());

			// Number conversion
			String s1 = "abc";
			int convertedInt = Integer.parseInt(s1);
			System.out.println("Converted integer : "
					+ convertedInt);

			// Array operation
			char[] ch = new char[4];
			ch[7] = 'B';
		}
		catch(ArithmeticException aex) {

			// corresponding handling code,
			// if any exception from try block
			aex.printStackTrace();
		}
		catch(NullPointerException npex) {

			// corresponding handling code,
			// if any exception from try block
			System.out.println(npex.toString());
		}
		catch(NumberFormatException nfex) {

			// corresponding handling code,
			// if any exception from try block
			System.out.println(nfex.toString());
		}
		catch(ArrayIndexOutOfBoundsException aioobex) {

			// corresponding handling code,
			// if any exception from try block
			System.out.println(aioobex.toString());
		}
		finally {

			// finally block always gets executed
			// for code clean-up activities

			System.out.println("finally block"
					+ " always gets executed");
			// rest of the code clean-up
		}
	}
}

Output:

java.lang.ArithmeticException: / by zero
finally block always gets executed
	at in.bench.resources.exception.handling
	.MultipleCatchBlockForDifferentTypesOfException
	.main(MultipleCatchBlockForDifferentTypesOfException.java:12)

Explanation:

In the above program,

  • multiple catch blocks are provided for catching different types of exception
  • Different types of exception used are ArithmeticException, NullPointerException, NumberFormatException and ArrayIndexOutOfBoundsException
  • So, if any particular exception is raised then that corresponding catch-block will come into play by providing respective handler-code
  • Here, we have simply printed stack trace in the console for user information but in real-time scenarios we can provide different handler-code (depending on the business requirements)

1.2 Shortcomings of above program for try with multiple catch blocks:

  • Although,handler code for each type of exception is same still we have to provide multiple catch blocks
  • Providing multiple catch blocks increases length of the program/code
  • Which reduces readability of the program/code

2. Multi-catch block

  • To overcome above shortcoming of try with multiple catch blocks
  • Sun people (now Oracle group) introduced new feature called multi-catch block in Java 1.7 version
  • Reason : to group different types of exception into single catch-block separating each exception-type by pipe character (|)

2.1 Java 1.7 version onwards:

  • Using multi-catch block, we can write/code single catch block to handle multiple types of exceptions

2.2 Pseudo code for multi-catch blocks:

try {
	// code which might raise exception
}
catch(ArithmeticException |
		NullPointerException |
		NumberFormatException |
		ArrayIndexOutOfBoundsException ex) {
	// handling code for any type of exception from try block
	ex.printStackTrace();
}

2.3 Example on Multi-Catch block

  • Let us re-write the same example using multi-catch block

MultiCatchBlockExampleInJava7.java

package in.bench.resources.exception.handling;

public class MultiCatchBlockExampleInJava7 {

	public static void main(String[] args) {

		try {

			// code which might raise exception

			// arithmetic operation
			int result = 18/0;
			System.out.println("Result of division : "
					+ result);

			// String operation
			String str = null;
			System.out.println("Lenght of the String : "
					+ str.length());

			// Number conversion
			String s1 = "abc";
			int convertedInt = Integer.parseInt(s1);
			System.out.println("Converted integer : "
					+ convertedInt);

			// Array operation
			char[] ch = new char[4];
			ch[7] = 'B';
		}
		catch(ArithmeticException |
				NullPointerException |
				NumberFormatException |
				ArrayIndexOutOfBoundsException ex) {
			// handling code
			// for any type of exception from try block
			ex.printStackTrace();
		}
	}
}

2.4 Advantages of using multi-catch block in Java 1.7 version:

  • By using multi-catch block, we can handle different types of exceptions thrown from try-block in a single multi-catch block
  • By doing so, length of the program/code is decreased when comparing with multiple catch blocks for each types of exception
  • Which makes readability far improved
  • Note: with multi-catch block, different types of exception can be grouped which ultimately provide the same handler code
  • Otherwise, it is worth to go back and write/code multiple catch blocks for different types of exception where handler-code doesn’t going to remain same in the program

2.5 Rules for using multi-catch block in Java 1.7 version:

  1. There shouldn’t be any relationship betweendeclared exception-type in multi-catch block. Otherwise, compile-time error will be thrown stating “The exception <child-exception-type> is already caught by the alternative <parent-exception-type>”
  2. If a catch block handles more than one exception-type (i.e.; multi-catch block), then exception variable is implicitly final. Any changes or re-assignment within catch block results in compile-time error

Let us discuss each case individually with examples

Rule 1: No relationship between different exception-types declared in the multi-catch block

  • When multiple exception-type is declared inside multi-catch block, then there shouldn’t be any relationship between exception-types
  • If there exists any relationship, like parent-to-child or child-to-parent then compile-time error will be thrown stating “The exception <child-exception-type> is already caught by the alternative <parent-exception-type>”
  • Declaring same exception-type twice in a single multi-catch block results in compile-time error stating “The exception <same-exception-type> is already caught by the alternative <same-exception-type>”
  • Go through below screen captures for different cases

Case 1.1: Parent to Child relationship between different exception-types in multi-catch block

  • Compile-time error: The exception ArithmeticException is already caught by the alternative Exception

Case 1.2: Child to Parent relationship between different exception-types in multi-catch block

  • Compile-time error: The exception NullPointerException is already caught by the alternative Exception

Case 1.3: Same type of exception in multi-catch block

  • Compile-time error: The exception NullPointerException is already caught by the alternative NullPointerException

Rule 2: Variable of a multi-catch block handling more than one exception-type is implicitly final

  • Variable declared for handling different types of exception in single multi-catch block is implicitly final
  • In the below example, exception variable ex is implicitly final
  • Changing or re-assigning this variable will results in compile-time error stating “The parameter <parameter-name> of a multi-catch block cannot be assigned

2.6 Best practice:

There is a possibility of program/code might raise multiple exceptions from try-block,

  • If handler code is same, then we can catch all types of exception in single multi-catch block
  • Otherwise, if handler code is different for different types of exception then it is better to provide multiple catch blocks (like in older version)
  • Or else it is very much possible to provide combination of both multiple catch blocks & single multi-catch block for handling different types of exceptions, starting Java 1.7 version

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Top Exception and Error
Java 7 - try-with-resources with examples