在 finally 中处理空连接

Handling a null Connection in finally(在 finally 中处理空连接)

本文介绍了在 finally 中处理空连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立了一个数据库连接.然后我尝试建立连接并在出现异常时返回.在代码的更下方,我有一个 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]
} 

这篇关于在 finally 中处理空连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 finally 中处理空连接

基础教程推荐