Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Multiple Catch Block and Nested Try-Catch Statements in Java

[post-views]

 

 

In this lesson, you will learn

  • Multiple Catch Statements
  • Nested try-catch Statements

 

Multiple Catch Statements

  • In Java, A single try block can have multiple catch blocks.
  • This feature allows you to handle different types of exceptions in different ways.
  • When an exception is thrown within the try block, Java checks each catch block in order and transfers control to the first catch block with a parameter that matches the type of the exception.
  • This mechanism enables more precise and varied handling of exceptions, making your code more robust and easier to debug.

 

Syntax: Multiple Catch Blocks

try {
    // Code that might throw multiple types of exceptions
} 
catch (ExceptionType1 e1) {
    // Handling code for ExceptionType1
} 
catch (ExceptionType2 e2) {
    // Handling code for ExceptionType2
}
/* You can have more catch blocks 
for additional exception types */

 

Example-1: Multiple Catch Block

public class MultipleCatchExample1 {
    public static void main(String[] args) {
    	int[] numbers = {5, 10, 15, 20, 25};
        int num=5;
        try {
        	int x=numbers[5] / num-numbers[1];
        	/* This line can throw both ArrayIndexOutOfBoundsException 
        	 * and ArithmeticException
        	 */
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds!");
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        }
        
        int y=numbers[1] / numbers[0];
        System.out.println("Y="+y);
    }
}

 

Output

Array index is out of bounds!
Y=2

 

Example-2: Multiple Catch Block

public class MulipleCatchExample2 {

	public static void main(String[] args) {
		try {
			int a = args.length;
			System.out.println("a = " + a);
			int b = 12 / a;
			int c[] = { 1 };
			c[12] = 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.");
	}
}

 

Output

Test Case-1: Without passing command line arguments

Run: java MulipleCatchExample2

a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.

 

Test Case-2: Passing command line arguments

Run: java MulipleCatchExample2 5

a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException: 
Index 42 out of bounds for length 1
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.

 

Let us understand this using an example.

/*
 * 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.
 */

public class MulipleCatchExample3 {

	public static void main(String[] args) {
		try {
			int x = 0;
			System.out.println("a = " + a);
			int b = 12 / a;
			int c[] = { 1 };
			c[12] = 99;
		} 
		catch (Exception e) {
			System.out.println("Generic Exception catch.");
		}
		//ERROR – the following exceptions are unreachable
		catch(ArithmeticException e) {
			System.out.println("Divide by 0: " + e);
		} 
		catch(ArrayIndexOutOfBoundsException e) {
			System.out.println("Array index oob: " + e);
		}
	}
}

 

Output

 

Nested try Statements

The try statement can be inside another try.

 

 

Syntax: Nested try-catch block

try {
    // Outer try block
    try {
        // Inner try block
    } catch (ExceptionType1 e1) {
        // Handling code for ExceptionType1
    }
} catch (ExceptionType2 e2) {
    // Handling code for ExceptionType2
}

 

Example: Nested try-catch

<pre class="wp-block-syntaxhighlighter-code">public class NestedTryExample1 {
	
	public static void main(String[] args) {
		try {
			int x = args.length;
			/* If no command-line args are present,
			 * the following statement will generate 
			 * a divide-by-zero exception. */
			
			 int y = 12 / x;
			 System.out.println("x = " + x);
			 
			 try { // nested try block
			 /* If one command-line arg is used,
			  * then a divide-by-zero exception 
			  * will be generated by the following code. */
				 
				 if(x==1) x = x/(x-x); // division by zero
				 /* If two command-line args are used,
				  * then generate an out-of-bounds exception. */
				 
				 if(x==2) {
					 int numbers[] = {1,2,3,4,5};
					 numbers[12] = 20; // generate an out-of-bounds exception
				 }
			 } 
			 catch(ArrayIndexOutOfBoundsException e) {
				 System.out.println("Array index out-of-bounds: " + e);
			 }
		} //outer try close
		catch(ArithmeticException e) {
			System.out.println("Divide by 0: " + e);
		}
	}
}<br /><br /></pre>

Output

 

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review

 

 

Layer 1
Login Categories