简体   繁体   中英

How to check if a parameter is null

I'm trying to test for null parameters but you cannot compare an object to null.

The following is dead code:

    } else if(x == null){
        throw new NullPointerException("Parameter is null");
    }

How do I rewrite it to gain the desired effect?

To use handle in the Java literal sense of the word

Foo foo = bar.couldReturnNull();
try {
   foo.doSomething();
} catch (NullPointerException e) {
   System.out.println("bar.couldReturnNull() returned null");
   throw new NullPointerException();
}

In Java you can compare to the value null. The standard way to do this is as follows:

String s = null;
if(s == null)
{  
    //handle null
}  

Typically throwing an NPE is a poor practice in the real world.

You don't say explicitly, but this looks like Java because of the NullPointerException. Yes, you can compare an object reference to null, and so this code is fine. You might be mixing it up with SQL, where nothing compares equal to null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM