Java обработка нескольких исключений

Is it possible in Java to catch two exceptions in the same catch block? [duplicate]

I need to catch two exceptions because they require the same handling logic. I would like to do something like:

catch (Exception e, ExtendsRuntimeException re) < // common logic to handle both exceptions >

Have a look at docs.oracle.com/javase/7/docs/technotes/guides/language/… for more Java 7 enhancements. I’m a little surprised this question and it’s answers received so many up votes.

6 Answers 6

Java 7 and later

Multiple-exception catches are supported, starting in Java 7.

try < // stuff >catch (Exception1 | Exception2 ex) < // Handle both exceptions >

The static type of ex is the most specialized common supertype of the exceptions listed. There is a nice feature where if you rethrow ex in the catch, the compiler knows that only one of the listed exceptions can be thrown.

Java 6 and earlier

Prior to Java 7, there are ways to handle this problem, but they tend to be inelegant, and to have limitations.

Approach #1

try < // stuff >catch (Exception1 ex) < handleException(ex); >catch (Exception2 ex) < handleException(ex); >public void handleException(SuperException ex) < // handle exception here >

This gets messy if the exception handler needs to access local variables declared before the try . And if the handler method needs to rethrow the exception (and it is checked) then you run into serious problems with the signature. Specifically, handleException has to be declared as throwing SuperException . which potentially means you have to change the signature of the enclosing method, and so on.

Approach #2

try < // stuff >catch (SuperException ex) < if (ex instanceof Exception1 || ex instanceof Exception2) < // handle exception >else < throw ex; >> 

Once again, we have a potential problem with signatures.

Approach #3

try < // stuff >catch (SuperException ex) < if (ex instanceof Exception1 || ex instanceof Exception2) < // handle exception >> 

If you leave out the else part (e.g. because there are no other subtypes of SuperException at the moment) the code becomes more fragile. If the exception hierarchy is reorganized, this handler without an else may end up silently eating exceptions!

Источник

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.

Читайте также:  Прохождение по массиву java

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.
Читайте также:  METANIT.COM

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.

Источник

Поймать множественные исключения в Java

Поймать множественные исключения в Java

  1. Перехват нескольких исключений с помощью нескольких операторов перехвата в Java
  2. Перехват множественных исключений с помощью instanceOf в Java
  3. Перехват множественных исключений в блоке перехвата с помощью | в Java

Сегодня мы рассмотрим способы использования и перехвата множественных исключений в Java. Исключение в Java возникает, когда во время выполнения происходит нежелательное событие. Самый распространенный способ увидеть исключение — использовать ключевые слова try-catch. Здесь try содержит блок кода, который нужно проверить, а catch содержит код, показывающий, когда возникает исключение.

Мы рассмотрим три метода использования нескольких исключений в одной ловушке на следующих примерах.

Перехват нескольких исключений с помощью нескольких операторов перехвата в Java

В этом примере мы берем два входа типа int от пользователя и затем разделяем их, чтобы показать результат. Обратите внимание, что мы заключили этот код в блок try ; Значит, в нем тоже должен быть блок catch .

Могут быть сгенерированы множественные исключения, такие как InputMismatchException , когда введенное значение не относится к типу int , и ArithmeticException , когда num2 получает значение ноль, потому что ни одно число не делится на ноль. Мы можем выбросить Exception , которое является родительским для всех остальных исключений.

Чтобы поймать их всех, мы пишем три разных блока catch с их типами исключений и распечатываем сообщение, чтобы показать, когда это исключение возникает. Выходные данные показывают разные результаты, когда нет исключения и когда есть исключения.

import java.util.InputMismatchException; import java.util.Scanner;  public class MultiExceptions   public static void main(String[] args)   System.out.println("Enter two numbers: ");  Scanner sc = new Scanner(System.in);  try    System.out.println("num1: ");  int num1 = sc.nextInt();   System.out.println("num2: ");  int num2 = sc.nextInt();   int dividedNum = num1 / num2;   System.out.println("After division result: " + dividedNum);   > catch (InputMismatchException e1)   System.out.println("Error! - Please enter a number.");  > catch (ArithmeticException e2)   System.out.println("Error! - You cannot divide any number with 0");  > catch (Exception e3)   System.out.println("An error occurred please try again!");  >  > > 
Enter two numbers: num1: 10 num2: 2 After division result: 5 
Enter two numbers: num1: 50 num2: hhh Error! - Please enter a number. 
Enter two numbers: num1: 10 num2: 0 Error! - You cannot divide any number with 0 

Перехват множественных исключений с помощью instanceOf в Java

Другой метод, который вы можете использовать, включает использование функции instanceOf , которая проверяет, принадлежит ли объект данному типу или нет; он возвращает логическое значение. Мы используем тот же пример, что и выше, но здесь мы используем один блок catch с несколькими операторами if.

Как обсуждалось выше, Exception является родительским классом для наиболее распространенных исключений. Мы можем использовать его объект, чтобы проверить, принадлежит ли выброшенное исключение заданному типу. Здесь мы рассматриваем два исключения: InputMismatchException и ArithmeticException .

import java.util.InputMismatchException; import java.util.Scanner;  public class MultiExceptions   public static void main(String[] args)   System.out.println("Enter two numbers: ");  Scanner sc = new Scanner(System.in);  try    System.out.println("num1: ");  int num1 = sc.nextInt();   System.out.println("num2: ");  int num2 = sc.nextInt();   int dividedNum = num1 / num2;   System.out.println("After division result: " + dividedNum);   > catch (Exception e)   if (e instanceof InputMismatchException)   System.out.println("Error! - Please enter a number.");  > else if (e instanceof ArithmeticException)   System.out.println("Error! - You cannot divide any number with 0");  > else   System.out.println("An error occurred please try again!");  >  >  > > 
Enter two numbers: num1: d Error! - Please enter a number. 

Перехват множественных исключений в блоке перехвата с помощью | в Java

В Java 7 и более поздних версиях мы можем использовать вертикальную черту или побитовое ИЛИ , чтобы записать несколько исключений в одном перехвате. В этом примере мы делим два введенных числа, а затем проверяем, истинно ли одно из двух исключений. Если это правда, будет напечатано сообщение об ошибке.

import java.util.InputMismatchException; import java.util.Scanner;  public class MultiExceptions   public static void main(String[] args)   System.out.println("Enter two numbers: ");  Scanner sc = new Scanner(System.in);  try    System.out.println("num1: ");  int num1 = sc.nextInt();   System.out.println("num2: ");  int num2 = sc.nextInt();   int dividedNum = num1 / num2;   System.out.println("After division result: " + dividedNum);   > catch (InputMismatchException | ArithmeticException e)   System.out.println("An error occurred please try again");  >  > > 
Enter two numbers: num1: f An error occurred please try again 

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Сопутствующая статья — Java Exception

Источник

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