Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between getCause and getNextException in SQLException?

Tags:

java

jdbc

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?

like image 291
danidiaz Avatar asked Jun 29 '13 08:06

danidiaz


People also ask

What are the different types of exceptions in JDBC?

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.

Is SQLException a subclass of Exception?

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.

Is SQLException part of exception?

SQLException is a specialized exception derived from Exception . If you catch Exception , all exception shall get caught.

What does SQL exception mean?

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 .


1 Answers

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 SQLExceptions. The head of this chain is the exception that is thrown. To get to the other SQLExceptions 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.

like image 70
Mark Rotteveel Avatar answered Sep 28 '22 04:09

Mark Rotteveel