Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Quick/Elegant way to check for null

In the program I'm currently writing, I find myself doing the following a lot...

Map<String,List<String>> network = loadSerializedObj(file); // null if failed
if(network != null) {
    anonNet = util.anonymize(newNet);
} else {
    // Some sort of error handling.
    System.out.println("Some sort of error message. Exiting...");
    System.exit(0);        
}

Is there a more succinct way of handling the event that loading the serialized object from file doesn't work and the method returns null? Any tips at all are welcome. Anywhere I can make this more elegant?

like image 651
well actually Avatar asked Dec 28 '22 23:12

well actually


2 Answers

you should make loadSerializedObj throw an exception instead of return null. you can return null when you don't have anything to return. when something breaks, you should throw an exception.

like image 133
jtahlborn Avatar answered Jan 04 '23 15:01

jtahlborn


In this case you can use the exception catch.

Map<String,List<String>> network = loadSerializedObj(file); // null if failed
try {
    anonNet = util.anonymize(newNet);
} catch(NullPointerException npe) {
    System.out.println("Some sort of error message. Exiting...");
    System.exit(0);        
}

but you must specify the util.anonymize to throw the NullPointerException if it does not it yet.

like image 42
Rafael Melo Macieira Avatar answered Jan 04 '23 16:01

Rafael Melo Macieira