简体   繁体   中英

spring jdbcTemplate how to catch exception?

Everything is brilliant until I encounter place where I actually do need to catch exception. When I place

jdbcTemplate.query(something...)

in

try{}

block I get:

 Unreachable catch block for SQLException. This exception is never thrown from the try statement body. 

What do I do in this situation?

try{
    personIdReturnedByDb = jdbcTemplate.queryForInt(sql, p.getEmail(),
            p.getName(), p.getSurname(), encPw, dateSql);
}

catch(SQLException sa){


}

Thank You,

That's because SQLException , a checked exception, is not thrown by the any of the JdbcTemplate.query(...) methods ( javadoc link) . Spring translates this to one of the DataAccessException , which is more generic family of runtime exceptions, in order to abstract away any specific underlying database implementation.

You should catch the JdbcTemplate exception

ie

try
{
   // Your Code 
}
catch (InvalidResultSetAccessException e) 
{
    throw new RuntimeException(e);
} 
catch (DataAccessException e)
{
    throw new RuntimeException(e);
}

InvalidResultSetAccessException is a DataAccessException so that no need to catch it in your case. And DataAccessException is already a RuntimeException so that no need to throw a Runtime exception. But you should throw a specific exception of your application such as :

try
{
   // Your Code 
}
catch (DataAccessException e)
{
    throw new MyApplicationException("A problem occurred while retrieving my data", e);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM