0

I never use it so I'm wondering about the usefulness of the finally block.

What's the difference between

try {
    // A
} catch(...) {
    // B
} finally {
    // C
}

and

try {
    // A
} catch(...) {
    // B
}
// C

In both cases :

if no exceptions -> A,C

if exceptions -> A,B,C

tweetysat
  • 2,187
  • 14
  • 38
  • 75

2 Answers2

1

There will be a difference if A throws an exception not caught in catch or if the catch block throws an exception.

Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
-2

Can be used to close/free resource after exception has occurred. Example java function bellow.

public static ArrayList foo(Connection conn) throws SQLException {
    ArrayList results = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {   
        // create a query, perform the query and
        // process the results
    } finally {
        try {
             rs.close();
        } catch(SQLException ex) {
            throw new RuntimeException(ex);
        }
        try {
            ps.close();
       } catch(SQLException ex) {
           throw new RuntimeException(ex);
       }
    }
    return results;
}