Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
like image 375
Rakesh Avatar asked Aug 16 '10 05:08

Rakesh


People also ask

Is try catch faster than if else?

If you've one if/else block instead of one try/catch block, and if an exceptions throws in the try/catch block, then the if/else block is faster (if/else block: around 0.0012 milliseconds, try/catch block: around 0.6664 milliseconds). If no exception is thrown with a try/catch block, then a try/catch block is faster.

Is it better to use if else or try catch?

You should use if / else to handle all cases you expect. You should not use try {} catch {} to handle everything (in most cases) because a useful Exception could be raised and you can learn about the presence of a bug from it.

What is faster if or try?

Python3. Now it is clearly seen that the exception handler ( try/except) is comparatively faster than the explicit if condition until it met with an exception. That means If any exception throws, the exception handler took more time than if version of the code.

Does Try Catch affect performance?

try/catch will only effect performance if an Exception is thrown (but that still isn't because of try/catch , it is because an Exception is being created). try/catch/finally does not add any additional overhead over try/catch .


1 Answers

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.

like image 154
Mitch Wheat Avatar answered Oct 05 '22 23:10

Mitch Wheat