Tutorial

Java Catch Multiple Exceptions, Rethrow Exception

Published on August 3, 2022
author

Pankaj

Java Catch Multiple Exceptions, Rethrow Exception

In Java 7, catch block has been improved to handle multiple exceptions in a single catch block. If you are catching multiple exceptions and they have similar code, then using this feature will reduce code duplication. Let’s understand java catch multiple exceptions feature with an example.

Java catch multiple exceptions

java catch multiple exceptions, java rethrow exceptions Before Java 7, we used to catch multiple exceptions one by one as shown below.

catch (IOException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
catch (SQLException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
}

In Java 7, we can catch both these exceptions in a single catch block as:

catch(IOException | SQLException ex){
     logger.error(ex);
     throw new MyException(ex.getMessage());
}

If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can’t change it. The byte code generated by this feature is smaller and reduce code redundancy.

Java rethrow exception

Another improvement is done in Compiler analysis of rethrown exceptions. Java rethrow exception allows you to specify more specific exception types in the throws clause of a method declaration. Let’s see this with a small example:

package com.journaldev.util;

public class Java7MultipleExceptions {

	public static void main(String[] args) {
		try{
			rethrow("abc");
		}catch(FirstException | SecondException | ThirdException e){
			//below assignment will throw compile time exception since e is final
			//e = new Exception();
			System.out.println(e.getMessage());
		}
	}

	static void rethrow(String s) throws FirstException, SecondException,
			ThirdException {
		try {
			if (s.equals("First"))
				throw new FirstException("First");
			else if (s.equals("Second"))
				throw new SecondException("Second");
			else
				throw new ThirdException("Third");
		} catch (Exception e) {
			//below assignment disables the improved rethrow exception type checking feature of Java 7
			// e=new ThirdException();
			throw e;
		}
	}

	static class FirstException extends Exception {

		public FirstException(String msg) {
			super(msg);
		}
	}

	static class SecondException extends Exception {

		public SecondException(String msg) {
			super(msg);
		}
	}

	static class ThirdException extends Exception {

		public ThirdException(String msg) {
			super(msg);
		}
	}

}

As you can see that in rethrow method, catch block is catching Exception but it’s not part of throws clause. Java 7 compiler analyze the complete try block to check what types of exceptions are thrown and then rethrown from the catch block. Note that this analysis is disabled if you change the catch block argument. Further Reading: Exception Handling in Java.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
March 30, 2019

In Java 8 exception parameter can be changed in multi catch block?

- Coder

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 18, 2019

    Write a program which takes the age of 5 persons from command line and find the average age of all persons. The program should handle exception if the argument is not correctly formatted and custom exception if the age is not between 1 to 100.

    - siddharth

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      June 19, 2018

      what is the use again we have to re catch exceptions from where we called the method

      - Dileep

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        January 11, 2016

        Hi Pankaj, Note to add here if there is hierarchy of exceptions in catch block then we need to catch base exception only, can’t write child and parent exception in same catch with pipe, it will give compilation error. e.g. catch (IOException | Exception e){} will say IOException already caught by the alternative Exception.

        - Tanu

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          April 22, 2014

          hellow pankaj , can u please explain more abt overloading and overriding… because i always use to get confuse between these two

          - phintsho

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            April 22, 2014

            i dont understand the throws exception so please pankaj can u explain …

            - phintsho

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 5, 2014

              Hi pankaj, i really dont understand the code for rethrowing an exception in java7.could you please explain the code in detail.

              - indra

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                January 7, 2014

                Hi Pankaj, if i want to throw different exception message based on exception catched then how to do that? ex: if sql exception then i want send message as failed to insert into table and number excpetion then input provided is not a valid number then how to use single catch block?

                - Ashok

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  July 23, 2013

                  Hi Pankaj, Using single catch block how can I differentiate from where my code is getting exception? try{} catch(IOException ie){ ie.printStackTrace();} catch(SQLException se){ se.printStackTrace();} catch(Exception e){ e.printStackTrace();} now it is replaced with catch(IOException| SQLException |Exception e){ e.printStackTrace();} In the above code my doubt is e.printStackTrace() will print which exception class message whether (IOException / SQLException/Exception )?

                  - subrat panda

                    Try DigitalOcean for free

                    Click below to sign up and get $200 of credit to try our products over 60 days!

                    Sign up

                    Join the Tech Talk
                    Success! Thank you! Please check your email for further details.

                    Please complete your information!

                    Become a contributor for community

                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                    DigitalOcean Documentation

                    Full documentation for every DigitalOcean product.

                    Resources for startups and SMBs

                    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                    Get our newsletter

                    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                    New accounts only. By submitting your email you agree to our Privacy Policy

                    The developer cloud

                    Scale up as you grow — whether you're running one virtual machine or ten thousand.

                    Get started for free

                    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                    *This promotional offer applies to new accounts only.