Skip to content

Java Core

Can I use try-finally block (without catch)?

Yes, you can use the try-finally construction. As a use case, we can try to connect to a database and finally we will close the connection:

Connection connection = null;

try {
    connection = Database.getConnection();
    // some operations
} finally {
    try {
        if (connection != null) {
            connection.close();
        }
    } catch(SomeException e) {
        // what to do
    }
}

This code looks a bit redundant. But in Java 7 we can use a try-with-resources block to handle our resources closing in a more convinient way…

Read More →