Rethrowing an exception in java

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.

Читайте также:  Hello World

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.

  1. Open your text editor and type in the following Java statements:Java Source for Rethrowing an ExceptionThe 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).
  2. Save your file as RethrowAnException.java .
  3. 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 .Compile Source for Rethrow Exception
  4. Type in the command to run your program without providing a command line parameter and hit Enter .Run for Test Rethrow ExceptionWhen 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.
Читайте также:  Tree structures in php
  1. How to Check Object Type in Java
  2. How to Create a Jar File in Java
  3. How to Compile Packages in Java
  4. How to Throw an Exception in Java
  5. How to Create an Exception Class in Java
  6. How to Use the super Keyword to Call a Base Class Constructor in Java
  7. How to Use the Comparator.comparing Method in Java 8
  8. How to Use System.in in Java
  9. How to Call an Interface Method in Java
  10. How to Add a Time Zone in the Java 8 Date/Time API
  11. How to Rethrow an Exception in Java (this article)
  12. How to Use the instanceof Operator with a Generic Class in Java
  13. How to Instantiate an Object in Java
  14. How to Filter Distinct Elements from a Collection in Java 8
  15. How to Create a Derived Class in Java
  16. How to Skip Elements with the Skip Method in Java 8
  17. How to Create a Java Bean
  18. How to Implement an Interface in Java
  19. How to Compare Two Objects with the equals Method in Java
  20. How to Set PATH from JAVA_HOME
  21. How to Prevent Race Conditions in Java 8
  22. How to Write a Block of Code in Java
  23. How to Display the Contents of a Directory in Java
  24. How to Group and Partition Collectors in Java 8
  25. How to Create a Reference to an Object in Java
  26. How to Reduce the Size of the Stream with the Limit Method in Java 8
  27. How to Write an Arithmetic Expression in Java
  28. How to Format Date and Time in the Java 8 Date/Time API
  29. How to Use Comparable and Comparator in Java
  30. How to Break a Loop in Java
  31. How to Use the this Keyword to Call Another Constructor in Java
  32. How to Write a Unit Test in Java
  33. How to Declare Variables in Java
  34. How to Override Base Class Methods with Derived Class Methods in Java
  35. How to Use Serialized Objects in Java
  36. How to Write Comments in Java
  37. How to Implement Functional Interfaces in Java 8
  38. How to Write Type Parameters with Multiple Bounds in Java
  39. How to Add Type and Repeating Annotations to Code in Java 8
  40. How to Use Basic Generics Syntax in Java
  41. How to Map Elements Using the Map Method in Java 8
  42. How to Work with Properties in Java
  43. How to Write while and do while Loops in Java
  44. How to Use the finally Block in Java
  45. How to Write for-each Loops in Java
  46. How to Create a Method in Java
  47. How to Continue a Loop in Java
  48. How to Handle Java Files with Streams
  49. How to Create an Interface Definition in Java
  50. How Default Base Class Constructors Are Used with Inheritance
Читайте также:  Php parse email address

Training Options

Course Catalog

Источник

Java Catch Multiple Exceptions, Rethrow Exception

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

java catch multiple exceptions, java rethrow 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

Источник

Оцените статью