Handling a null Connection in finally

2019-02-27 12:28发布

问题:

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