Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Multiple Catch Block?
3.
Syntax of Multiple Catch Blocks
4.
How Multiple Catch Blocks Work
5.
Example 1: Using Multiple Catch Blocks with Different Exceptions
5.1.
Java
6.
Example 2: Catching Subclasses of Exception
6.1.
Java
7.
Frequently Asked Questions
7.1.
What is the difference between multiple catch blocks and a multi-catch block?
7.2.
Can we have nested try-catch blocks?
7.3.
How to handle multiple exceptions in Java 6 and earlier?
8.
Conclusion
Last Updated: Jul 26, 2024
Easy

Multiple Catch Block in Java

Author Gaurav Gandhi
0 upvote

Introduction

In Java, exception handling is an essential aspect of writing robust and error-free code. Exceptions are unwanted or unexpected events that disrupt the normal flow of a program. Java provides a powerful mechanism to handle these exceptions using try-catch blocks. Sometimes, we may need to handle multiple exceptions in a single try block, and that's where multiple catch blocks come into play. 

Multiple Catch Block in Java

This article will explore the concept of multiple catch blocks in Java, including their syntax, examples, and best practices.

What is a Multiple Catch Block?

A multiple catch block is used to handle more than one type of exception using multiple catch statements within a single try block. Each catch block catches a specific type of exception. This allows us to handle different exceptions separately and provide specific error messages or actions for each exception type.

Syntax of Multiple Catch Blocks

The syntax for using multiple catch blocks in Java is straightforward. Here's how it looks

try {
    // Code that may throw exceptions
} catch (ExceptionType1 e1) {
    // Handle exception of type ExceptionType1
} catch (ExceptionType2 e2) {
    // Handle exception of type ExceptionType2
} catch (ExceptionType3 e3) {
    // Handle exception of type ExceptionType3
}


Each catch block is checked in the order they appear, and the first matching catch block is executed.

How Multiple Catch Blocks Work

When an exception occurs in the try block, the JVM checks each catch block from top to bottom to find a matching exception type. Once a matching catch block is found, it executes the code inside that catch block. If no matching catch block is found, the program terminates.

Example 1: Using Multiple Catch Blocks with Different Exceptions

Here is an example of using multiple catch blocks to handle different exceptions:

  • Java

Java

public class MultipleCatchExample {

   public static void main(String[] args) {

       try {

           int[] numbers = {1, 2, 3};

           System.out.println(numbers[3]); // This will throw ArrayIndexOutOfBoundsException

           int result = 10 / 0; // This will throw ArithmeticException

       } catch (ArrayIndexOutOfBoundsException e) {

           System.out.println("Array index is out of bounds!");

       } catch (ArithmeticException e) {

           System.out.println("Arithmetic error: Division by zero!");

       } catch (Exception e) {

           System.out.println("An unexpected error occurred.");

       }

   }

}
You can also try this code with Online Java Compiler
Run Code


Explanation:

  • The try block contains code that may throw exceptions.
     
  • The first catch block handles ArrayIndexOutOfBoundsException.
     
  • The second catch block handles ArithmeticException.
     
  • The third catch block handles any other exceptions.
     

Output:

Array index is out of bounds!

Example 2: Catching Subclasses of Exception

Here's an example showing how to handle exceptions that are subclasses of a common exception type:

  • Java

Java

public class SubclassCatchExample {

   public static void main(String[] args) {

       try {

           String str = null;

           System.out.println(str.length()); // This will throw NullPointerException

       } catch (NullPointerException e) {

           System.out.println("Null pointer exception occurred!");

       } catch (Exception e) {

           System.out.println("An unexpected error occurred.");

       }

   }

}
You can also try this code with Online Java Compiler
Run Code


Explanation:

  • The try block contains code that may throw a NullPointerException.
     
  • The first catch block handles NullPointerException.
     
  • The second catch block is a generic catch-all for any other exceptions.
     

Output:

Null pointer exception occurred!

Frequently Asked Questions

What is the difference between multiple catch blocks and a multi-catch block?

Multiple catch blocks handle different exceptions in separate catch statements. A multi-catch block handles multiple exceptions in a single catch statement using the | operator.

Can we have nested try-catch blocks?

Yes, try-catch blocks can be nested to handle exceptions at different levels of code execution.

How to handle multiple exceptions in Java 6 and earlier?

In Java 6 and earlier, you must use multiple catch blocks, as the multi-catch block was introduced in Java 7.

Conclusion

Using multiple catch blocks in Java allows for handling different types of exceptions separately. This makes the code more readable and maintainable. By following best practices and understanding the flow of control, you can effectively manage exceptions in your Java programs.

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass