1

Is it fine to have a nested try block without a catch or finally block and let the outer catch block handle the exception if any from the nested try block?

Something like:

try (Connection con = ds.getConnection();
     PreparedStatement ps = con.prepareStatement(sql);) {

    //nested try block without a catch or finally block
    try (ResultSet rs = ps.executeQuery();) {
        while (rs.next()) {
            list.add(rs.getInt("id"));
        }
    }
} catch (SQLException e) {
    e.printStackTrace();
}
Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
Ashish Sood
  • 192
  • 12
  • @sr.Varoa my question here isn't related to whether it compiles or not. it sure compiles. my question is, is it fine to follow a programming practice of not declaring a catch block for nested try block. Although with this approach the program compiles and run fine. – Ashish Sood May 15 '16 at 07:32

2 Answers2

0

If you remove the 'try' the result set will not close automatically.

The try-with-resources statement sort of executes rs.close in a hidden finally.

It is good practice to close the resultset, open resultset can lead to problems : java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

Problem with exception catching in this example is how do you differentiate between datasource exceptions, query creation exceptions or query execution SQLExceptions? I would probably throw a specific RuntimeException when my datasource can not deliver an connection.

Community
  • 1
  • 1
Sand
  • 16
  • 2
-1

No. Your code won't compile.
Every try block (even nested) must be followed with catch(..) and/or finally.

In your case add a second catch block if you want to handle any other additional exceptions.

Sample code:

try {
    // code which may throw exceptions
} catch(Exception e1) {
    // e1 specific code
} catch (Exception e2) {
    // e2 specific code
} finally {
   // Optional. Executes whether exception thrown or not!
}
Bhargav Kumar R
  • 2,190
  • 3
  • 22
  • 38