throws Exception in finally blocks

后端 未结 15 2323
慢半拍i
慢半拍i 2020-11-29 18:04

Is there an elegant way to handle exceptions that are thrown in finally block?

For example:

try {
  // Use the resource.
}
catch( Excep         


        
15条回答
  •  自闭症患者
    2020-11-29 18:30

    As of Java 7 you no longer need to explicitly close resources in a finally block instead you can use try-with-resources syntax. 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.

    Assume the following code:

    try( Connection con = null;
         Statement stmt = con.createStatement();
         Result rs= stmt.executeQuery(QUERY);)
    {  
         count = rs.getInt(1);
    }
    

    If any exception happens the close method will be called on each of these three resources in opposite order in which they were created. It means the close method would be called first for ResultSetm then the Statement and at the end for the Connection object.

    It's also important to know that any exceptions that occur when the close methods is automatically called are suppressed. These suppressed exceptions can be retrieved by getsuppressed() method defined in the Throwable class.

    Source: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

提交回复
热议问题