Which one is faster:
Either this
try { n.foo(); } catch(NullPointerException ex) { }
or
if (n != null) n.foo();
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.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With