Java Reference
In-Depth Information
try {
// perform database tasks
} catch (java.sql.SQLException){
// perform exception handling
}
How It Works
A standard try-catch block can be used to catch java.sql.Connection or
java.sql.SQLException exceptions. Your code will not compile if these excep-
tions are not handled, and it is a good idea to handle them properly in order to prevent
your application from crashing if one of these exceptions is thrown. Almost any work
that is performed against a java.sql.Connection object will need to contain er-
ror handling to ensure that database exceptions are handled correctly. In fact, nested
try-catch blocks are often required to handle all the possible exceptions. You need
to ensure that connections are closed once work has been performed and the Connec-
tion object is no longer used. Similarly, it is a good idea to close
java.sql.Statement objects for memory allocation cleanup as well.
Because Statement and Connection objects need to be closed, it is common
to see try-catch-finally blocks used to ensure that all resources have been ten-
ded to as needed. It is not unlikely that you will see older JDBC code that resembles
the following style:
try {
// perform database tasks
} catch (java.sql.SQLException ex) {
// perform exception handling
} finally {
try {
// close Connection and Statement objects
} catch (java.sql.SQLException ex){
// perform exception handling
}
}
Newer code should be written to take advantage of the try-with-resources
statement, which allows one to offload resource management to Java, rather than per-
Search WWH ::




Custom Search