The previous example of using a try-with-resources statement can be re-written with resource objects created in the same context as follows:
Connection conn;
ResultSet rs;
try {
conn = DriverManager.getConnection("dburl", "username", "password");
rs = conn.createStatement().executeQuery("select * from some_table");
} catch (SQLException e) {
e.printStackTrace();
return;
}
try (conn; rs) {
while (rs.next()) {
//process the retrieved data
}
} catch (SQLException ex) {
//Do something
//The exception was probably caused by incorrect SQL statement
}
We have to deal with SQLException because it is a checked exception, and getConnection(), createStatement(), executeQuery(), and next() methods declare it in their throws clause. Here is an example:
Statement createStatement() throws SQLException;
It means...