Multiple catch block (Java 7+) Rules


Pre-Requisite: Java: Exception Handling Tutorial

Java 7 improved multi catch to handle in single block so that reduce the number of lines of code. Here we will discuss about the rules  to handle multi catch block and difference while implementing multi catch with Java 7+.

Multi Catch Rules

Java Catch Exception Rules
5 Rules for Catching Exceptions in Java (7+)

Here you will know all above multiple catch block rules in details:

Rule 1 : One try block can associated with multiple catch blocks.

As per exception handling one try block safe guard can associated with multiple catch block to handle different type of exception depend on code statement on try block. Like below handling ArithmeticException and NumberFormatException in different catch blocks. You can see complete example in end of this blog.

try
{
//some code here
}
catch (ArithmeticException ex)
{
System.out.println("Arithmetic " + ex);
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}

Rule 2 : If the exceptions have parent-child relationship, the catch blocks must be sorted by the most specific exceptions first, then by the most general ones.

In this below example FileNotFoundException is sub class of IOException thats what most specific exception FileNotFoundException will always come before IOException.

try {
	File file = new File("ABC.txt");
	BufferedReader br = new BufferedReader(new FileReader(file));

	String st;
	while ((st = br.readLine()) != null)
		System.out.println(st);

	} catch (FileNotFoundException ex) {
		ex.printStackTrace();
	} catch (IOException ex) {
		ex.printStackTrace();
	}

Rule 3 : If the exceptions are not in the same inheritance tree, i.e. they don’t have parent-child relationship, the catch blocks can be sorted any order.

As exception handling blocks ArithmeticException and NumberFormatException i are not having any relation like parent and child , so order sequence of these two exceptions doesn’t matter. Like in rule 1 we use as order ArithmeticException and NumberFormatException while in this rule using order as  NumberFormatException  and ArithmeticException.

try
{
//some code here
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}
catch (ArithmeticException ex)
{
System.out.println("Arithmetic " + ex);
}

Rule 4 : If we catch the most general exception first, then we also catch other exceptions which are sub-types of the general exception.

If we are using generic Exception or RuntimeException to handle all type of exception this catch block should always be in last. otherwise compiler will throw exception as  “Unreachable catch block for ArithmeticException

Wrong way

multi catch error for generic exception

Right Way

try
{
//some code here
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}
catch (Exception ex)
{
//To handle all othertype exception exception NumberFormatException<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
System.out.println("Exception" + ex);
}

Rule 5 : In java 7 multiple exceptions can be handle throw single block when need to print or throw some generic exception.

Since Java 7,  we can combine multiple  exceptions in single catch clause by pipe (|) symbol. Below code is equivalent to code as above in legacy way.

try
{
//some code here
}
catch (ArithmeticException|NumberFormatException ex)
{
 System.out.println("Exception Encountered " + ex);
 }

While applying above Java 7+ multi catch .We have to follow below rules:

  • Rule 1: Multi catch is for exceptions with different hierarchy.
  • Rule 2: Can not re-assign value to catch parameter in multi-catch.
  • Rule 3: In Java 7, Exception will not handle all exception.

Below are running example with legacy way of multi catch and Java 7+.

Multi cath block example

import java.util.Scanner;

public class MultiCatchTest {
/**
 * In the following code, we have to handle two different exceptions but take same action for both. So we needed to have two different catch blocks as of Java 6.0.
 * @param args
 */
	public static void main(String[] args) {
		 System.out.println("Please enter a integer value :");
		 Scanner scn = new Scanner(System.in);
	        try
	        {
	            int n = Integer.parseInt(scn.nextLine());
	            if (99%n == 0)
	                System.out.println(n + " is a factor of 99");
	        }
	        catch (ArithmeticException ex)
	        {
	            System.out.println("Arithmetic " + ex);
	        }
	        catch (NumberFormatException ex)
	        {
	            System.out.println("Number Format Exception " + ex);
	        }
	}
}

Output


Please enter a integer value :
0
Arithmetic java.lang.ArithmeticException: / by zero

Please enter a integer value :
3.5
Number Format Exception java.lang.NumberFormatException: For input string: "3.5"

Multi catch block example with (Java 7 +)

import java.util.Scanner;

public class MultiCatchTest7 {

	public static void main(String[] args) {
		  //After JAVA 7
        /**
         * single catch block to catch multiple exceptions by separating each with | (pipe symbol) in catch block.
         */
		 System.out.println("Please enter a integer value :");
		  Scanner scn = new Scanner(System.in);
        try
        {
            int n = Integer.parseInt(scn.nextLine());
            if (99%n == 0)
                System.out.println(n + " is a factor of 99");
        }
        catch (ArithmeticException|NumberFormatException ex)
        {
            System.out.println("Exception Encountered " + ex);
        }
	}
}

Output


Please enter a integer value :
0
Exception Encountered java.lang.ArithmeticException: / by zero

Please enter a integer value :
3.5
Exception Encountered java.lang.NumberFormatException: For input string: "3.5"

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s