try-catch-finally在Java问题中抛出异常

Mik*_*e55 0 java exception try-catch-finally

我是Java初学者,但我认为在使用try-catch-finally时我不必使用声明异常throws SQLException.但是,如果我不使用它,编译器会给我错误:

"未报告的异常java.sql.SQLException;必须被捕获或声明被抛出".

我包含了一个catch,所以我不确定为什么会出现这种错误.

public static ResultSet getResultSet ( String query ) 
{
    dbConn = getConnection();

    try
    {
       stmt = dbConn.createStatement( );

       ResultSet rs = stmt.executeQuery( query );

       return rs;
    }
   catch (SQLException ex)
   {
       return null;
   }
   finally
   {
       stmt.close();
       dbConn.close();
   }
}
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 9

这是因为close()方法:

stmt.close();
dbConn.close();
Run Code Online (Sandbox Code Playgroud)

可能会抛出SQLException并且您没有将它们封装在try/catch块中.

方法很可能会在finally子句中抛出异常,并且在没有catch-clause处理这些异常的情况下,必须声明该方法抛出这些异常.

基本上,你需要做类似的事情

finally
{
    try {
        stmt.close();
    } catch (SQLException sqle) {
        // log the statement-close exception
    }

    try {
        dbConn.close();
    } catch (SQLException sqle) {
        // log the connection-close exception
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不,基本上你需要把每个`close()`放在它自己的**`try-catch`中,它记录或忽略异常.在你的例子中,如果`stmt.close()`抛出,那么`dbConn.close()`永远不会发生. (2认同)
  • 您可能还想添加nullchecks. (2认同)