Java catch multiple exception in one catch



Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking

This page covers the following topics:

Handling More Than One Type of Exception

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:

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:

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:

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 :

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:

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.
Читайте также:  Error with code 601 in

—>

Источник

Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking

This page covers the following topics:

Handling More Than One Type of Exception

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:

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:

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:

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 :

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:

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.
Читайте также:  Ct program burner error 0x1106

—>

Источник

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.

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

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:

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.

If you’ve enjoyed this tutorial and our broader community, consider checking out our DigitalOcean products which can also help you achieve your development goals.

Источник

The catch Blocks

You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.

Each catch block is an exception handler that handles the type of exception indicated by its argument. The argument type, ExceptionType , declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name .

The catch block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler’s argument.

The following are two exception handlers for the writeList method:

Exception handlers can do more than just print error messages or halt the program. They can do error recovery, prompt the user to make a decision, or propagate the error up to a higher-level handler using chained exceptions, as described in the Chained Exceptions section.

Catching More Than One Type of Exception with One Exception Handler

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.

In the catch clause, specify the types of exceptions that block can handle, and separate each exception type 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.

Источник

Try-Catch

This article describes how to use try-catch and finally block in Java.

The try-catch statement is used to catch exceptions. The checked and unchecked exceptions can be caught both.

A try block is a place where a checked or an unchecked exception can be thrown. A catch block handles an exception. It defines the exception’s type and a reference to it.

1. Simple Try-Catch Block

Rules for writing try-catch:

  • Only one try block is allowed.
  • More than one catch block can be written.
  • The catch blocks should immediately follow the try block.
  • The catch blocks should all follow each other, without any other statements or blocks in between them.
  • It is illegal to use a try block without either a catch block or a finally block.
  • A finally block should immediately follow the last catch block (or it must immediately follow the try block if there is no catch).
Читайте также:  Error querying ocsp responder

Example 1.1. Catching an unchecked Exception

Let’s look at the simple example where an unchecked exception is caught. In line 4 StringIndexOutOfBoundsException is thrown and the execution is transferred to line 6. So the line 5 is never executed in this example.

Example 1.2. Catching multiple unchecked Exceptions

Let’s rewrite the previous example to be executed without throwing exceptions. In this case, all lines of the try block are run and the execution is transferred to line 11. Additionally, it is added one more catch block:

2. Using Finally

A finally block is optional. It contains the code that is always executed after the try block, whether an exception was thrown or not. The finally block won’t be executed only if it is called System.exit(). In this case, the program will terminate abnormally without executing the finally block.

  • If the try block executes with no exceptions, the finally block is executed immediately after the try block completes.
  • If there was an exception thrown, the finally block executes immediately after the proper catch block completes.
  • If there is a return statement in the try block, the finally block executes right after the return statement is encountered, and before the return executes.
  • If an exception is re-thrown inside the catch block, a finally block will be executed.

If the finally block is present, the catch block is optional. You can have both or either a catch block or a finally block.

Example 2.1. Using Finally Block

The example demonstrates how to use try block with finally. The catch block is absent:

Example 2.2. Using Try-Catch Block with Finally

Let’s rewrite Example 1.1 adding finally block:

3. Exceptions Handling

The catch block will catch not only exceptions of the specified class but it’s subclassed as well.

For example, class IndexOutOfBoundsException has two subclasses: ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException. We can rewrite the Example 1.2 using one catch block with IndexOutOfBoundsException:

Example 3.1. Handle multiple Exceptions by one Catch Block

If a code in the try block throws ArrayIndexOutOfBoundsException or StringIndexOutOfBoundsException, the exception will be handled.

If an exception can be caught in several catch blocks, the exception will be caught by the first defined catch block.

Moreover, the hierarchy of the classes should be paid attention to — a catch block with a subclass should be defined before a catch block with the superclass.

Example 3.2. Handle multiple Subclasses Exceptions

The code in the example has two catch blocks for Exception and IOException, which is the subclass of Exception. If the IOException is thrown, the only first catch block will be executed.

Some previous examples define catch blocks for an unchecked exception, which, in fact, cannot be thrown in the try block. But it is illegal to define a catch block for a checked exception that isn’t thrown by the code in the try block.

Example 3.3. Illegal Definition of the Catch Block for a checked Exception

This example won’t compile because the try block doesn’t contain code to throw checked IOException:

4. Try-with-Resources in Java 7

The try-with-resources block is available since Java 7. It gives the possibility to declare one or more resources in the try block so they can be closed without doing it explicitly in a finally block.

  • We can use any object that implements java.lang.AutoCloseable as a resource.
  • Resources declared inside a try-with-resources cannot be used outside this block (they’re out of scope and they’re closed after the try block ends).
  • If the try block also throws an exception, the exception from the try block «wins» and the exceptions from the close() method are «suppressed».

Example 4.1. Using AutoCloseable Resource in the Try-with-Resources Statement

The BufferedReader instance is declared in a try-with-resource statement. It will be closed regardless of whether the try statement completes normally or not.

It is possible to declare more than one resource in a try-with-resource statement. They have to be separated by a semicolon:

Example 4.2. Multiple Resources in the Try-with-Resources Statement

5. Handle Multiple Exceptions in one Block

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.

If a catch block handles more than one exception type, then the catch parameter is implicitly final.

It is possible to combine exceptions in a multi-catch block that are not directly related (regarding inheritance)

Источник

Оцените статью
toolgir.ru
Adblock
detector