Java suppressed exception что это



The try-with-resources Statement

The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable , which includes all objects which implement java.io.Closeable , can be used as a resource.

The following example reads the first line from a file. It uses an instance of FileReader and BufferedReader to read data from the file. FileReader and BufferedReader are resources that must be closed after the program is finished with it:

In this example, the resources declared in the try -with-resources statement are a FileReader and a BufferedReader . The declaration statements of these resources appear within parentheses immediately after the try keyword. The classes FileReader and BufferedReader , in Java SE 7 and later, implement the interface java.lang.AutoCloseable . Because the FileReader and BufferedReader instances are declared in a try -with-resource statement, they will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException ).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try -with-resources statement:

However, this example might have a resource leak. A program has to do more than rely on the garbage collector (GC) to reclaim a resource’s memory when it’s finished with it. The program must also release the resoure back to the operating system, typically by calling the resource’s close method. However, if a program fails to do this before the GC reclaims the resource, then the information needed to release the resource is lost. The resource, which is still considered by the operaing system to be in use, has leaked.

In this example, if the readLine method throws an exception, and the statement br.close() in the finally block throws an exception, then the FileReader has leaked. Therefore, use a try -with-resources statement instead of a finally block to close your program’s resources.

If the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. In contrast, in the example readFirstLineFromFile , if exceptions are thrown from both the try block and the try -with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try -with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.

The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:

In this example, the try -with-resources statement contains two declarations that are separated by a semicolon: ZipFile and BufferedWriter . When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the BufferedWriter and ZipFile objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.

The following example uses a try -with-resources statement to automatically close a java.sql.Statement object:

The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API.

Note: A try -with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try -with-resources statement, any catch or finally block is run after the resources declared have been closed.

Читайте также:  Mikrotik ssl error no cypher overlap

Suppressed Exceptions

An exception can be thrown from the block of code associated with the try -with-resources statement. In the example writeToFileZipFileContents , an exception can be thrown from the try block, and up to two exceptions can be thrown from the try -with-resources statement when it tries to close the ZipFile and BufferedWriter objects. If an exception is thrown from the try block and one or more exceptions are thrown from the try -with-resources statement, then those exceptions thrown from the try -with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContents method. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.

Classes That Implement the AutoCloseable or Closeable Interface

See the Javadoc of the AutoCloseable and Closeable interfaces for a list of classes that implement either of these interfaces. The Closeable interface extends the AutoCloseable interface. The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception . Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException , or no exception at all.

Источник

Class Throwable

Instances of two subclasses, Error and Exception , are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).

A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Over time, a throwable can suppress other throwables from being propagated. Finally, the throwable can also contain a cause: another throwable that caused this throwable to be constructed. The recording of this causal information is referred to as the chained exception facility, as the cause can, itself, have a cause, and so on, leading to a «chain» of exceptions, each caused by another.

One reason that a throwable may have a cause is that the class that throws it is built atop a lower layered abstraction, and an operation on the upper layer fails due to a failure in the lower layer. It would be bad design to let the throwable thrown by the lower layer propagate outward, as it is generally unrelated to the abstraction provided by the upper layer. Further, doing so would tie the API of the upper layer to the details of its implementation, assuming the lower layer’s exception was a checked exception. Throwing a «wrapped exception» (i.e., an exception containing a cause) allows the upper layer to communicate the details of the failure to its caller without incurring either of these shortcomings. It preserves the flexibility to change the implementation of the upper layer without changing its API (in particular, the set of exceptions thrown by its methods).

A second reason that a throwable may have a cause is that the method that throws it must conform to a general-purpose interface that does not permit the method to throw the cause directly. For example, suppose a persistent collection conforms to the Collection interface, and that its persistence is implemented atop java.io . Suppose the internals of the add method can throw an IOException . The implementation can communicate the details of the IOException to its caller while conforming to the Collection interface by wrapping the IOException in an appropriate unchecked exception. (The specification for the persistent collection should indicate that it is capable of throwing such exceptions.)

Читайте также:  Authorization required error code

A cause can be associated with a throwable in two ways: via a constructor that takes the cause as an argument, or via the initCause(Throwable) method. New throwable classes that wish to allow causes to be associated with them should provide constructors that take a cause and delegate (perhaps indirectly) to one of the Throwable constructors that takes a cause. Because the initCause method is public, it allows a cause to be associated with any throwable, even a «legacy throwable» whose implementation predates the addition of the exception chaining mechanism to Throwable .

By convention, class Throwable and its subclasses have two constructors, one that takes no arguments and one that takes a String argument that can be used to produce a detail message. Further, those subclasses that might likely have a cause associated with them should have two more constructors, one that takes a Throwable (the cause), and one that takes a String (the detail message) and a Throwable (the cause).

Источник

Подавленные исключения Java

Узнайте о подавленных исключениях в Java и о том, как с ними работать.

Автор: Amy DeGregorio
Дата записи

1. введение

В этом кратком руководстве мы узнаем о подавленных исключениях в Java. Короче говоря, подавленное исключение-это исключение, которое выбрасывается, но каким-то образом игнорируется. Распространенный сценарий для этого в Java-это когда блок finally создает исключение. Любое исключение, первоначально возникшее в блоке try , затем подавляется.

Начиная с Java 7, теперь мы можем использовать два метода в классе Throwable для обработки подавленных исключений: addSuppressed и getSuppressed . Следует отметить, что конструкция try-with-resources также была введена в Java 7. В наших примерах мы увидим, как они связаны.

2. Подавленные исключения в действии

2.1. Сценарий Подавленного исключения

Давайте начнем с быстрого рассмотрения примера, в котором исходное исключение подавляется исключением, возникающим в блоке finally :

Пока мы указываем путь к существующему файлу, никаких исключений не будет, и метод будет работать так, как ожидалось.

Однако предположим, что мы предоставляем файл, который не существует:

В этом случае блок try вызовет исключение FileNotFoundException при попытке открыть несуществующий файл. Поскольку файл В объекте никогда не был инициализирован, он вызовет исключение NullPointerException , когда мы попытаемся закрыть его в нашем блоке finally . Наш вызывающий метод получит только исключение NullPointerException , и будет не совсем очевидно, в чем заключалась первоначальная проблема: что файл не существует.

2.2. Добавление Подавленного Исключения

Теперь давайте посмотрим, как мы можем воспользоваться преимуществами метода Throwable.addSuppressed для предоставления исходного исключения:

Давайте перейдем к нашему модульному тесту и посмотрим, как getSuppressed работает в этой ситуации:

Теперь у нас есть доступ к этому исходному исключению из массива подавленных исключений.

2.3. Использование try-with-resources

Наконец, давайте рассмотрим пример использования try-with-resources , где метод close вызывает исключение. Java 7 представила конструкцию try-with-resources и интерфейс AutoCloseable для управления ресурсами.

Во-первых, давайте создадим ресурс, который реализует Автоклавируемый :

Далее, давайте используем наш Исключительный ресурс в блоке try-with-resources :

Наконец, давайте перейдем к нашему модульному тесту и посмотрим, как вытрясаются исключения:

Следует отметить, что при использовании AutoCloseable , это исключение, вызванное в методе close , которое подавляется . Возникает исходное исключение.

3. Заключение

В этом коротком уроке мы узнали, что такое подавленные исключения и как они происходят. Затем мы увидели, как использовать методы addSuppressed и get Suppressed для доступа к этим подавленным исключениям. Наконец, мы увидели, как работают подавленные исключения при использовании блока try-with-resources .

Как всегда, пример кода доступен на GitHub .

Читайте также:  Проверка интерфейса victoria buffer error

Источник

Class Throwable

Instances of two subclasses, Error and Exception , are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).

A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Over time, a throwable can suppress other throwables from being propagated. Finally, the throwable can also contain a cause: another throwable that caused this throwable to be constructed. The recording of this causal information is referred to as the chained exception facility, as the cause can, itself, have a cause, and so on, leading to a «chain» of exceptions, each caused by another.

One reason that a throwable may have a cause is that the class that throws it is built atop a lower layered abstraction, and an operation on the upper layer fails due to a failure in the lower layer. It would be bad design to let the throwable thrown by the lower layer propagate outward, as it is generally unrelated to the abstraction provided by the upper layer. Further, doing so would tie the API of the upper layer to the details of its implementation, assuming the lower layer’s exception was a checked exception. Throwing a «wrapped exception» (i.e., an exception containing a cause) allows the upper layer to communicate the details of the failure to its caller without incurring either of these shortcomings. It preserves the flexibility to change the implementation of the upper layer without changing its API (in particular, the set of exceptions thrown by its methods).

A second reason that a throwable may have a cause is that the method that throws it must conform to a general-purpose interface that does not permit the method to throw the cause directly. For example, suppose a persistent collection conforms to the Collection interface, and that its persistence is implemented atop java.io . Suppose the internals of the add method can throw an IOException . The implementation can communicate the details of the IOException to its caller while conforming to the Collection interface by wrapping the IOException in an appropriate unchecked exception. (The specification for the persistent collection should indicate that it is capable of throwing such exceptions.)

A cause can be associated with a throwable in two ways: via a constructor that takes the cause as an argument, or via the initCause(Throwable) method. New throwable classes that wish to allow causes to be associated with them should provide constructors that take a cause and delegate (perhaps indirectly) to one of the Throwable constructors that takes a cause. Because the initCause method is public, it allows a cause to be associated with any throwable, even a «legacy throwable» whose implementation predates the addition of the exception chaining mechanism to Throwable .

By convention, class Throwable and its subclasses have two constructors, one that takes no arguments and one that takes a String argument that can be used to produce a detail message. Further, those subclasses that might likely have a cause associated with them should have two more constructors, one that takes a Throwable (the cause), and one that takes a String (the detail message) and a Throwable (the cause).

Источник

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