在 finally 中处理空连接

2022-01-24 00:00:00 connection java

我建立了一个数据库连接.然后我尝试建立连接并在出现异常时返回.在代码的更下方,我有一个 finally 块,我打算将其用作全部捕获以关闭连接.

I establish a database connection. I then try to make the connection and return if there is an exception. Further down in the code I have a Finally block that I intend to use as a catch all to close the connection.

Connection con = null;
try{
  try{
     con = connectDB();
  }
  catch{
     return;
  }
  ...code
catch{
  return;
}
finally{
    con.close();
} 

但是,如果初始连接失败,它会跳转到 finally 块,我的 con.close() 会在该块中引发空指针异常.解决这个问题的最佳方法是什么?有没有办法测试 con 是否为空?我试过 if(con.isValid(0)) 和 con.equals(null) 和 con == null,它们都不起作用.

However, if the initial connect fails, it jumps to the Finally block where my con.close() throws a null pointer exception. What is the best way to get around this? Is there a way to test if the con is null? I've tried if(con.isValid(0)) and con.equals(null) and con == null, none of them work.

推荐答案

Connection 实现了 AutoClosable,因此您可以使用 try-with-resources 声明.

Connection implements AutoClosable so you can use a try-with-resources statement.

try (Connection con = connectDB()) {
    [some code]
} 

相关文章