显示try catch和finally的Java JDBC异常例子

・1 分钟阅读

java/JDBC try/catch/finally异常常见问题解答:可以向我展示一个如何在try/catch/finally块中捕获JDBC异常的例子吗?

这是一个JDBC示例,显示了一些使用try/catch/finally块的Java代码:

 public String getContactEmail(int contactNumber)
 throws SQLException
 {
 Connection connection = null;
 PreparedStatement doSelect = null;
 try
 {
 String contactEmail = null;
 String selectStatement =\"SELECT contact_email FROM store WHERE contact_id = ?\";
 connection = ConnectionPool.getConnection();
 doSelect = connection.prepareStatement(selectStatement);
 doSelect.setInt(1,contactNumber);
 ResultSet rs = doSelect.executeQuery();
 if ( rs.next() )
 {
 contactEmail = rs.getString(1);
 return contactEmail;
 }
 else
 {
 return null;
 }
 }
 catch (SQLException se)
 {
 // log the exception
 log.error(se);
 // re-throw the exception
 throw se;
 }
 finally
 {
 try
 {
 doSelect.close();
 ConnectionPool.freeConnection(connection);
 }
 catch (Exception e)
 {
 }
 }
 }

查询发生在try块中,catch块捕获发生的SQLException,打印错误消息,然后抛出异常,finally子句确保所有资源在结束时都被清除。

Xn_warm profile image