Handling a null Connection in finally

流过昼夜 提交于 2019-12-02 05:08:14

问题


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

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.


回答1:


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

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



回答2:


if (con.isValid(0))

can't work, if con is null. you would be calling a member of a null-variable, causing a NullPointerException.

The same goes for

con.equals(null)

Now,

if ( con == null )

does work, but you want the negative comparison:

if ( con != null )

instead.




回答3:


You can use con != null or Objects.nonNull(con) to check if the connection object is not null before closing it inside finally block as shown below:

Connection con = null;
try{
     con = connectDB();
     //add your code
  catch{
      //log exception
      return;
  } finally {
    if(Objects.nonNull(con)) { //or use con != null
        con.close();
    }
}

Or else you can also use try-with-resources (because Connection implements AutoCloseable) as shown below:

try(Connection con = connectDB()) {
   //code
catch {
   return;
}


来源:https://stackoverflow.com/questions/43791277/handling-a-null-connection-in-finally

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!