Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Frame work Wraps Checked Exceptions inside RuntimeExceptions

Have this method call:

   ->
    simpleJdbcTemplate.queryForInt(SQL,null);
   ->

queryForInt() method in the springs SimpleJdbcTemplate throws a DataAccessException which is a runtime exception. I want to propegate exceptions to the view tier of the application since Spring frame work Wraps Checked Exceptions inside RuntimeExceptions I stuck here.

How do I do this?

Explanation 1:

The value-add provided by the Spring Framework's JDBC abstraction framework- they say The Spring Framework takes care of all except 3 and 6. 3 and 6 need to be coded by an application developer

  1. Define connection parameters

  2. Open the connection

  3. Specify the statement

  4. Prepare and execute the statement

  5. Set up the loop to iterate through the results (if any)

  6. Do the work for each iteration

  7. Process any exception

  8. Handle transactions

  9. Close the connection

But if I encounter a situation where the connection to the database losses after certain time the program started. Then a runtime exception will be thrown when a call to the above method made.since I don't handle the exception I cannot inform the user interface (view).

like image 727
Buddhi Avatar asked Jan 23 '23 14:01

Buddhi


2 Answers

Just because Spring throws a runtime exception doesn't mean you cannot catch it. If you want to do something special for DataAccessExceptions, you can certainly do that:

try {
    // query logic
} catch (DataAccessException ex) {
    // handle the exception
}

If you're using Spring's MVC framework, it may be worth looking into the ExceptionResolver interface. It's a mechanism for deciding how to handle all those uncaught exceptions thrown by the lower layers of the application. It gives you one last chance to display a different view based on exceptions that are thrown.

like image 163
David Avatar answered Jan 28 '23 18:01

David


It depends if your view tier catches checked exceptions (any subclass of throwable that does not subclass RuntimeException or Error, or are not instances of RuntimeException or Error directly) or unchecked exceptions (RuntimeException or Errors or subclasses of these Throwable subclasses).

Generally, you'll either have something like this:

try {
//... processing
} catch(Exception/RuntimeException e) {
// propagate the exception to the view in a meaningful manner
}

If this is the case, for a runtime exception, you don't have to do anything - the block will catch the runtime exception.

If you want to convert it to checked, assuming you're using a version of Java that supports wrapped exceptions, all you have to do is:

try {
//...spring code
} catch(DataAccessException e) {
throw new Exception(e);
}

Then, your layer above this processing will catch it as a checked exception.

like image 26
MetroidFan2002 Avatar answered Jan 28 '23 19:01

MetroidFan2002