在使用JdbcTemplate 时,若SQL语句执行遇到错误,则会在控制台中打印出SQLExecption 错误信息。
若想使用try…catch…捕获SQLExecption 异常,会发现无法捕获到该类型的异常,代码如下:
try{
// 使用JdbcTemplate访问数据库
}catch (SQLException e) {
// 异常处理
}
报错提示信息:Unreachable catch block for SQLException. This exception is never thrown from the try statement body.
解决方法:
捕获JdbcTemplate的异常
之所以无法捕获到SQLException 是因为JdbcTemplate 所抛出的异常类型有两种:
- InvalidResultSetAccessException :无效的结果集合访问异常
- DataAccessException :数据访问异常
try{
// 使用JdbcTemplate访问数据库
}catch (InvalidResultSetAccessException e){
throw new RuntimeException(e);
}catch (DataAccessException e){
throw new RuntimeException(e);
}
获取SQLException对象
虽然在SQL语句执行错误时我们能够捕获到DataAccessException 类型的异常对象,但如果需要获得SQL执行异常中包含的ErrorCode或Message信息仍需要SQLException才行。
因此需要通过DataAccessException获取SQLException,代码如下:
try{
// 使用JdbcTemplate访问数据库
}catch (DataAccessException e){
SQLException exception = (SQLException)e.getCause();
// 通过exception获取ErrorCode、Message等信息
}
原文:https://blog.csdn.net/lgj123xj/article/details/78868876