spring jdbcTemplate如何捕获exception?
一切都很棒,直到遇到我确实需要捕捉exception的地方。 当我放置
jdbcTemplate.query(something...)
在
try{}
块我得到:
Unreachable catch block for SQLException. This exception is never thrown from the try statement body.
在这种情况下我该怎么办?
try{ personIdReturnedByDb = jdbcTemplate.queryForInt(sql, p.getEmail(), p.getName(), p.getSurname(), encPw, dateSql); } catch(SQLException sa){ }
谢谢,
这是因为任何JdbcTemplate.query(...)
方法( javadoc链接)都不会抛出SQLException
(一个已检查的exception) 。 Spring将其转换为DataAccessException之一 ,这是更通用的运行时exception系列,以抽象出任何特定的底层数据库实现。
您应该捕获JdbcTemplateexception
即
try { // Your Code } catch (InvalidResultSetAccessException e) { throw new RuntimeException(e); } catch (DataAccessException e) { throw new RuntimeException(e); }