Looking at the SQLException javadocs, there seems to be an overlap between getCause
and getNextException
. The first returns a Throwable, but otherwise they seem to be pretty much interchangeable.
What is the difference between the two? When developing a JDBC driver, are there guidelines about when to choose one over the other as the exception chaining mechanism?
JDBC Exception handling is very similar to the Java Exception handling but for JDBC, the most common exception you'll deal with is java. sql. SQLException.
Exceptions that occurred due to the database are known as SQLException. We have a separate class for SQLException which is a subclass of Exception. We have the methods to get to know about the SQL exception more specific. The methods are getMessage(), getErrorCode(), getSQLState(), getNextException and printStackTace.
SQLException is a specialized exception derived from Exception . If you catch Exception , all exception shall get caught.
An exception that provides information on a database access error or other errors. Each SQLException provides several kinds of information: a string describing the error. This is used as the Java Exception message, available via the method getMesasge .
The method getCause()
gives you the cause - if any - of that specific SQLException
. On the other hand during processing it is entirely possible that multiple exceptions occur, think of batch processing, serverside errors for multiple query parameters (eg too long, conversion errors etc).
These multiple exceptions are on the same level (they are not each others cause), so they are added to a chain of SQLException
s. The head of this chain is the exception that is thrown. To get to the other SQLException
s in the chain, you use getNextException()
. Eg
try {
// Something that produces multiple SQLExceptions
} catch (SQLException e) {
SQLException current = e;
do {
// do something with current
} while ((current = current.getNextException()) != null)
}
On the other hand, a SQLException
also has a method public Iterator<Throwable> iterator()
(introduced in Java 6/JDBC4), this iterates over each SQLException
and their causes before proceeding to the next SQLException
in the chain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With