Java try catch several exceptions

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.

try < >catch (ExceptionType name) < >catch (ExceptionType name)

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:

try < >catch (IndexOutOfBoundsException e) < System.err.println("IndexOutOfBoundsException: " + e.getMessage()); >catch (IOException e)

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.

Читайте также:  Python очистить папку от файлов

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 ( | ):

catch (IOException|SQLException ex)

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.

Источник

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.

Источник

Java try catch several exceptions

Сама работа с исключениями мне понятна, но как это применяется на реальной практике? Типо, мы может поймать ошибку, сделать с ней что-то, чтобы программа могла продолжить свою работу, я так понимаю?

господа! может с какой-то версии обработка стала другой? это код (предпоследний пример из лекции выше) падает при выполнении и в вебе и у меня в idea

 В примере ниже возникший ArithmeticException будет перехвачен в первом catch, т.к. классы всех исключений унаследованы от Exception. Т.е. Exception захватывает любое исключение. try < System.out.println("Before method1 calling."); int a = 1/0; System.out.println("After method1 calling. Never will be shown."); >catch (Exception e) < System.out.println("Any other errors. Exception has been caught."); >catch (ArithmeticException e)

с ошибкой ArithmeticException has already been caught но если catch (Exception e) переставить в конец — то всё ок. т.е. компилятор хочет чтобы мы расставляли ошибки по иерархии, общие — в конце.

На моем уровне понимания, в последнем примере программа вообще может упасть, если в названии метода забыли указать, что он бросает ошибки которые отличаются от NPE

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

Неплохая по восприятию лекция,но по-моему все как-то тривиально,не правда ли? Можно эту инфу отдельно не выделять было? Хотя авторам виднее и спасибо им за их труд!

А есть ли разница как перехватывать исключение с помощью catch (Exception e) или catch (тип исключения e)? Ведь и так и так исключение будет перехвачено.

Образное Объяснение (стек вызовов + выброс исключения): Представьте себе, что открывая браузер, вы сами запускаетесь как программа: в стеке вызовов под вас обработчик выделяет новый блок памяти. Начинаете с метода main (например у вас на стартовой странице портал mail.ru) Для обработки каждой вкладки вашему ИИ требуется запускать отдельный метод: 1-метод: читаете анонс статьи, потом переходите по ссылке в другую вкладку; 2 метод: там читаете статью, вас что-то заинтересовывает, и в новой вкладке вы вбиваете новый запрос; 3 метод: смотрите видео по теме — третья вкладка; 4 метод: узнаете о новом интересном блогере и переходите на его канал — четвёртая; 5 метод: видите что у него в дружественных каналах есть интересная тема; 6 метод: переходите и запускаете приветственное видео в следующей вкладке; 7 метод: видите в рекомендациях видео по теме, которая давно вас интересовала. Переходите по ссылке и смотрите; . И так с каждой открытой вкладкой (или точнее с каждым вызванным методом) ваш стек растёт.

В какой-то момент вы понимаете, что из всего этого надо выбираться. Вы не можете сразу попасть в первый метод, вам сначала нужно завершить текущий (то есть досмотреть видео). Вы его досматриваете (или проматываете вылавливая только суть), и дальше закрываете вкладку. Вот тут метод 7 завершается и вы возвращаетесь в —> метод 6 — быстро просматриваете страницу и закрываете шестую вкладку и возвращаетесь в —> метод 5 . и так далее закрывая вкладки вы попадаете во все методы завершая гештальты каждый метод по очереди. Четвертый, третий, второй, первый и наконец вы возвращаетесь в main — это страница с которой всё началось (портал mail.ru). Вы выдыхаете и закрываете браузер. Всё, ваша программа завершилась. Вот примерно так работает стек вызовов. И если например в 6-м методе вы увидели нечто такое, что выбило вас из колеи и метод завершается аварийно, процесс возврата всё равно пройдет по всему стеку в самый низ, до метода main (чтобы собрать полный стек вызовов и вывести StackTrace в консоль). Так вот, чтобы такого не случилось, и программа не вылетала обратно на mail.ru с потерей всех данных, мы и перехватываем исключение прямо в том методе в котором оно возникло. В итоге программа аварийно вылетит только из одного метода и спокойно продолжит работать со следующей строчки кода после той где был вызван этот «плохой» метод.

Источник

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