Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting try/catch witouth inner catch block

I want to nest a try catch without having a catch in the inner try.
For example:

try (Connection conn = new Connection()) {
    //Fill preparedStatement etc
    try (ResultSet rs = conn.execute()){
    }
} catch (SQLException e) {
    //Log both exceptions here
}

Is this possible and is it a good practice?

like image 489
Luud van Keulen Avatar asked Mar 02 '26 15:03

Luud van Keulen


1 Answers

You can do this:

try (Connection conn = new Connection()) {
    ResultSet rs = conn.execute()
    // do stuff with rs
} catch (SQLException e) {
    // handle exception
}

Exceptions thrown by conn.execute() will be caught by the catch block. Exceptions thrown by new Connection() will be suppressed:

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.

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

EDIT: As Timothy pointed out, Connection does not guarantee to close a ResultSet it created. So we need something like this:

try (Connection conn = new Connection(); 
     Statement statement = connection.createStatement()) {

    // statement.set(....)

    try (ResultSet rs = conn.execute()) {
        // do stuff with rs
    }

} catch (SQLException e) {
    // handle exceptions
}
like image 118
Adriaan Koster Avatar answered Mar 05 '26 05:03

Adriaan Koster