Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is SQLException a checked exception [closed]

Tags:

People also ask

Is SQLException a checked exception?

1) Checked Exception The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.

Why is SQLException checked?

Making the SQLException checked is a way to force the developper to catch the Exception and wrap it in this new level of abstraction.

What is a SQLException in exception handling?

Answer: SQLException occurs if there is an error in the database access or other errors related to the database. When SQLException occurs, an object of type SQLException will be passed to the catch clause. We can handle it in the Catch block.

What type of exception is SQLException?

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 .


Can anyone think of a rational reason why SQLException is a checked exception?

Yes, there could be a syntax error in the query
Yes, the connection might have died
Yes, there might be a permission problem
Etc, etc blah blah blah

But practically 100% of the time (once you're running in production), there isn't any problem.

If there is a problem, the calling code can't do anything to recover, so for that reason it should be unchecked.

Being checked create masses of perfunctory try catch blocks throughout the code, as anyone who has been involved with a project that uses JDBC will attest. The code clutter is significant.

Because of the esoteric nature of SQL, the myriad of reasons you may get an SQLException and their complexity means you basically can not recover, unless the exception is caused by temporary network problem, but even then in a synchronous call, you're sunk anyway because you can't wait indefinitely for the network problem to be resolved, so you're going to have to fail the transaction.

Typically, calling SQL looks like this:

try {
    // make some SQL call(s)
} catch {SQLException e) { 
    // log the exception
    return; // and give up
}

Such code adds no value. There nothing reasonable you can do to recover. You might as well let a runtime exception bubble up - ie SQLException should be a runtime (unchecked) exception.