【问题标题】:spring jdbcTemplate how to catch exception?spring jdbcTemplate 如何捕获异常?
【发布时间】:2012-01-18 19:58:20
【问题描述】:

在我遇到我确实需要捕获异常的地方之前,一切都很棒。当我放置

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


}

谢谢,

【问题讨论】:

    标签: java jdbc


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      你应该捕获 JdbcTemplate 异常

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-11-27
          • 2012-04-06
          • 1970-01-01
          • 1970-01-01
          • 2019-08-07
          • 2019-04-17
          • 2018-09-02
          • 2012-11-10
          相关资源
          最近更新 更多