Why use finally instead of code after catch

code511788465541441 picture code511788465541441 · Jan 14, 2011 · Viewed 51.6k times · Source

Why do this

} catch (SQLException sqle) {
    sqle.printStackTrace();
} finally {
    cs.close();
    rs.close();
}

Instead of this

} catch (SQLException sqle) {
    sqle.printStackTrace();
}
rs.close();
cs.close();

Answer

JUST MY correct OPINION picture JUST MY correct OPINION · Jan 14, 2011

Because if an exception gets thrown no code after the try block is executed unless the exception is caught. A finally block is always executed no matter what happens inside your try block.