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)
这是因为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)