Spring JdbcTemplate如何捕获异常?

22
一切都很出色,直到我遇到需要捕获异常的地方。当我放置

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){


}

谢谢您,

3个回答

43
那是因为SQLException是一个已检查的异常,在任何JdbcTemplate.query(...)方法中都不会被抛出(javadoc link)。Spring将其转换为DataAccessException之一,这是更通用的运行时异常系列,以便抽象化任何特定的底层数据库实现。

8

您应该捕获JdbcTemplate异常

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

4

InvalidResultSetAccessException是DataAccessException的一种,因此在您的情况下不需要捕获它。 而DataAccessException已经是RuntimeException,所以不需要抛出RuntimeException。 但是,您应该抛出特定于您的应用程序的异常,例如:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接