spring jdbcTemplate how to catch exception?

后端 未结 3 1938
暖寄归人
暖寄归人 2020-12-31 03:39

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

jdbcTemplate.query(something...)

相关标签:
3条回答
  • 2020-12-31 04:07

    You should catch the JdbcTemplate exception

    i.e.

    try
    {
       // Your Code 
    }
    catch (InvalidResultSetAccessException e) 
    {
        throw new RuntimeException(e);
    } 
    catch (DataAccessException e)
    {
        throw new RuntimeException(e);
    }
    
    0 讨论(0)
  • 2020-12-31 04:17

    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);
    }
    
    0 讨论(0)
  • 2020-12-31 04:23

    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.

    0 讨论(0)
提交回复
热议问题