最终处理空连接 [英] Handling a null Connection in finally

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

问题描述

我建立了数据库连接。然后,我尝试建立连接并在有异常的情况下返回。在代码的更下方,我有一个Final模块,我打算将其用作捕获所有连接的工具。

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();
} 

但是,如果初始连接失败,它将跳转到Final块, con.close()引发空指针异常。解决此问题的最佳方法是什么?有没有办法测试con是否为null?我已经尝试过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.

推荐答案

连接实现 AutoClosable ,因此您可以使用尝试使用资源语句。

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

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

这篇关于最终处理空连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆