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

前端 未结 12 1986
暖寄归人
暖寄归人 2020-12-05 02:22

Which one is faster:

Either this

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

or

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


        
12条回答
  •  醉话见心
    2020-12-05 02:53

    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.

提交回复
热议问题