- Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
- Rethrowing Exceptions with More Inclusive Type Checking
- How to Rethrow an Exception in Java
- Related Articles
- Training Options
- Course Catalog
- Java Catch Multiple Exceptions, Rethrow Exception
- Java catch multiple exceptions
- Java rethrow exception
Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
Consider the following example, which contains duplicate code in each of the catch blocks:
catch (IOException ex) < logger.log(ex); throw ex; >catch (SQLException ex)
In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable ex has different types.
The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:
catch (IOException|SQLException ex)
The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar ( | ).
Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final . In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.
Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers.
Rethrowing Exceptions with More Inclusive Type Checking
The Java SE 7 compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the throws clause of a method declaration.
Consider the following example:
static class FirstException extends Exception < >static class SecondException extends Exception < >public void rethrowException(String exceptionName) throws Exception < try < if (exceptionName.equals("First")) < throw new FirstException(); >else < throw new SecondException(); >> catch (Exception e) < throw e; >>
This examples’s try block could throw either FirstException or SecondException . Suppose you want to specify these exception types in the throws clause of the rethrowException method declaration. In releases prior to Java SE 7, you cannot do so. Because the exception parameter of the catch clause, e , is type Exception , and the catch block rethrows the exception parameter e , you can only specify the exception type Exception in the throws clause of the rethrowException method declaration.
However, in Java SE 7, you can specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration. The Java SE 7 compiler can determine that the exception thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be FirstException and SecondException . Even though the exception parameter of the catch clause, e , is type Exception , the compiler can determine that it is an instance of either FirstException or SecondException :
public void rethrowException(String exceptionName) throws FirstException, SecondException < try < // . >catch (Exception e) < throw e; >>
This analysis is disabled if the catch parameter is assigned to another value in the catch block. However, if the catch parameter is assigned to another value, you must specify the exception type Exception in the throws clause of the method declaration.
In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:
- The try block is able to throw it.
- There are no other preceding catch blocks that can handle it.
- It is a subtype or supertype of one of the catch clause’s exception parameters.
The Java SE 7 compiler allows you to specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration because you can rethrow an exception that is a supertype of any of the types declared in the throws .
In releases prior to Java SE 7, you cannot throw an exception that is a supertype of one of the catch clause’s exception parameters. A compiler from a release prior to Java SE 7 generates the error, «unreported exception Exception ; must be caught or declared to be thrown» at the statement throw e . The compiler checks if the type of the exception thrown is assignable to any of the types declared in the throws clause of the rethrowException method declaration. However, the type of the catch parameter e is Exception , which is a supertype, not a subtype, of FirstException and SecondException . catch parameter, and the exception handled by this catch block is not reassigned, then these exception types are implicitly final . You may explicitly declare these exception types as final ; however this is not necessary:
catch (final IOException|SQLException ex)
Exception types that are not final (in particular, catch blocks in which the handled exception is reassigned) affect the features discussed on this page as follows:
- The compiler generates an error for catch blocks that handles more than one exception type.
- The compiler will not perform the more inclusive type checking for rethrown exceptions.
How to Rethrow an Exception in Java
An exception can be rethrown in a catch block. This action will cause the exception to be passed to the calling method. If the rethrow operation occurs in the main method then the exception is passed to the JVM and displayed on the console. The purpose of the rethrow operation is to get the attention of the outside world that an exception has occurred and at the same time perform any contingency logic (such as logging) in the catch block. To learn how to rethrow an exception in Java, follow these four steps.
- Open your text editor and type in the following Java statements:
The program attempts to access the first element of the args array. This array is populated with any command line parameters that were present when the program was started. If no command line parameters were provided by the console user, then an ArrayIndexOutOfBoundsException is thrown at runtime. This exception is caught by the program. A log entry is produced, then the exception is rethrown to the JVM (see line 9).
- Save your file as RethrowAnException.java .
- Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter .
- Type in the command to run your program without providing a command line parameter and hit Enter .
When the program attempts to access the args array, an ArrayIndexOutOfBoundsException is thrown. The catch block generates a log message to the console and then rethrows the exception to the JVM. The JVM displays the call stack trace for the exception on the console.
Related Articles
- How to Check Object Type in Java
- How to Create a Jar File in Java
- How to Compile Packages in Java
- How to Throw an Exception in Java
- How to Create an Exception Class in Java
- How to Use the super Keyword to Call a Base Class Constructor in Java
- How to Use the Comparator.comparing Method in Java 8
- How to Use System.in in Java
- How to Call an Interface Method in Java
- How to Add a Time Zone in the Java 8 Date/Time API
- How to Rethrow an Exception in Java (this article)
- How to Use the instanceof Operator with a Generic Class in Java
- How to Instantiate an Object in Java
- How to Filter Distinct Elements from a Collection in Java 8
- How to Create a Derived Class in Java
- How to Skip Elements with the Skip Method in Java 8
- How to Create a Java Bean
- How to Implement an Interface in Java
- How to Compare Two Objects with the equals Method in Java
- How to Set PATH from JAVA_HOME
- How to Prevent Race Conditions in Java 8
- How to Write a Block of Code in Java
- How to Display the Contents of a Directory in Java
- How to Group and Partition Collectors in Java 8
- How to Create a Reference to an Object in Java
- How to Reduce the Size of the Stream with the Limit Method in Java 8
- How to Write an Arithmetic Expression in Java
- How to Format Date and Time in the Java 8 Date/Time API
- How to Use Comparable and Comparator in Java
- How to Break a Loop in Java
- How to Use the this Keyword to Call Another Constructor in Java
- How to Write a Unit Test in Java
- How to Declare Variables in Java
- How to Override Base Class Methods with Derived Class Methods in Java
- How to Use Serialized Objects in Java
- How to Write Comments in Java
- How to Implement Functional Interfaces in Java 8
- How to Write Type Parameters with Multiple Bounds in Java
- How to Add Type and Repeating Annotations to Code in Java 8
- How to Use Basic Generics Syntax in Java
- How to Map Elements Using the Map Method in Java 8
- How to Work with Properties in Java
- How to Write while and do while Loops in Java
- How to Use the finally Block in Java
- How to Write for-each Loops in Java
- How to Create a Method in Java
- How to Continue a Loop in Java
- How to Handle Java Files with Streams
- How to Create an Interface Definition in Java
- How Default Base Class Constructors Are Used with Inheritance
Training Options
Course Catalog
Java Catch Multiple Exceptions, Rethrow Exception
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.
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
Before Java 7, we used to catch multiple exceptions one by one as shown below.
catch(IOException | SQLException ex)
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 us