The Wayback Machine - https://web.archive.org/web/20240724232531/https://www.geeksforgeeks.org/multicatch-in-java/
Open In App

Java Multiple Catch Block

Last Updated : 22 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Before Java 7, we had to catch only one exception type in each catch block. So, whenever we needed to handle more than one specific exception but take some action for all exceptions, we had to have more than one catch block containing the same code.

In the following code, we have to handle two different exceptions but take the same action for both. So we needed to have two different catch blocks as of Java 6.0.

Java




// A Java program to demonstrate that we needed
// multiple catch blocks for multiple exceptions
// prior to Java 7
 
import java.util.Scanner;
public class Test
{
    public static void main(String args[])
    {
        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);
        }
    }
}


Input 1: 

GeeksforGeeks

Output 1: 

Number Format Exception java.lang.NumberFormatException

For input string: "GeeksforGeeks"

Input 2: 

0

Output 2: 

Arithmetic Exception encountered java.lang.ArithmeticException: / by zero

Multiple Catch Block in Java

Starting from Java 7.0, it is possible for a single catch block to catch multiple exceptions by separating each with | (pipe symbol) in the catch block.

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 multiple exceptions, the catch parameter is implicitly final. This means we cannot assign any values to catch parameters.

Syntax:

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

Flow Chart of Java Multiple Catch Block


Java




// A Java program to demonstrate
// multicatch feature
 
import java.util.Scanner;
 
public class Test
{
    public static void main(String args[])
    {
        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 (NumberFormatException | ArithmeticException ex)
        {
            System.out.println("Exception encountered " + ex);
        }
    }
}


Input 1: 

GeeksforGeeks

Output 1:  

Exception encountered java.lang.NumberFormatException:

For input string: "GeeksforGeeks"

Input 2:  

0

Output 2:  

Exception encountered 

java.lang.ArithmeticException: / by zero

A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler. That is, the bytecode has no replication of exception handlers.

Important Points:  

1. If all the exceptions belong to the same class hierarchy, we should be catching the base exception type. However, to catch each exception, it needs to be done separately in their catch blocks.

2. Single catch block can handle more than one type of exception. However, the base (or ancestor) class and subclass (or descendant) exceptions can not be caught in one statement. For Example

// Not Valid as Exception is an ancestor of 
// NumberFormatException
catch(NumberFormatException | Exception ex)

3. All the exceptions must be separated by vertical bar pipe |.



Similar Reads

Java Try Catch Block
In Java exception is an "unwanted or unexpected event", that occurs during the execution of the program. When an exception occurs, the execution of the program gets terminated. To avoid these termination conditions we can use try catch block in Java. In this article, we will learn about Try, catch, throw, and throws in Java. Why Does an Exception o
4 min read
Catch block and type conversion in C++
Predict the output of following C++ program. C/C++ Code #include <iostream> using namespace std; int main() { try { throw 'x'; } catch(int x) { cout << " Caught int " << x; } catch(...) { cout << "Default catch block"; } } Output: Default catch block In the above program, a character 'x' is thrown and the
2 min read
Flow control in try catch finally in Java
In this article, we'll explore all the possible combinations of try-catch-finally which may happen whenever an exception is raised and how the control flow occurs in each of the given cases. Control flow in try-catch clause OR try-catch-finally clause Case 1: Exception occurs in try block and handled in catch blockCase 2: Exception occurs in try-bl
6 min read
Initialization of local variable in a conditional block in Java
Java comprises 5 conditional blocks namely - if, switch, while, for and try. In all these blocks, if the specified condition is true, the code inside the block is executed and vice-versa. Also, Java compiler doesn't let you leave a local variable uninitialized. While initializing local variable inside a conditional block, one must bear the followin
3 min read
Static Block and main() method in Java
In Java static block is used to initialize the static data members. Important point to note is that static block is executed before the main method at the time of class loading. This is illustrated well in the following example: // Java program to demonstrate that static // block is executed before main() class staticExample { // static block stati
2 min read
Block Lambda Expressions in Java
Lambda expression is an unnamed method that is not executed on its own. These expressions cause anonymous class. These lambda expressions are called closures. Lambda's body consists of a block of code. If it has only a single expression they are called "Expression Bodies". Lambdas which contain expression bodies are known as "Expression Lambdas". B
4 min read
Constructor Overloading with Static Block in Java
In Java, Constructor is a block of codes similar to the method that is used to initialize the object’s state. A constructor is invoked at the time of object or instance creation. Each time an object is created using a new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of
4 min read
Why You Need to Close the Java Streams in Finally Block?
In Java finally block is a block used to execute important and common code. The finally block is mostly used during exception handling with try and catch to close streams and files. The code in finally block is executed irrespective of whether there is an exception or not. This ensures that all the opened files are properly closed and all the runni
2 min read
How to Execute Instance Initialization Block (IIB) without Creating Object in Java?
In a Java program, operations can be performed on methods, constructors, and initialization blocks. Instance Initialization Blocks or IIB are used to initialize instance variables. We know that the instance block is the name-less method in java inside which we can define logic and they possess certain characteristics. Instance block logic is common
3 min read
The Initializer Block in Java
In order to perform any operations while assigning values to an instance data member, an initializer block is used. In simpler terms, the initializer block is used to declare/initialize the common part of various constructors of a class. It runs every time whenever the object is created. The initializer block contains the code that is always execut
2 min read
Practice Tags :
three90RightbarBannerImg