Which is faster, try catch or if-else in java (WRT performance)

Which one is faster:

Either this

try {
  n.foo();
} 
catch(NullPointerException ex) {
}

or

if (n != null) n.foo();

Answer

It’s not a question of which is faster, rather one of correctness.

An exception is for circumstances which are exactly that, exceptional.

If it is possible for n to be null as part of normal business logic, then use an if..else, else throw an exception.

Leave a Reply

Your email address will not be published. Required fields are marked *