What costs for sure less time for execution between the two options:
A:
if(something!=null){
...
}else{
//log
}
or:
B:
try{
something.getField();...
}catch(Exception e){
//log
}
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.
If you don't raise an exception your code will be faster with try except, otherwise it takes a little bit more time to treat the exception. In other word, if you are sure that your exception is extraodinary (it happens only in exceptional cases) it's cheaper for you to use try-except.
The key differences between exceptions and assertions are: Assertions are intended to be used solely as a means of detecting programming errors, aka bugs. By contrast, an exception can indicate other kinds of error or "exceptional" condition; e.g. invalid user input, missing files, heap full and so on.
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.
if
definitely.
Throwing an exception is a costly operation and this is not the purpose of Exception
.
The purpose of Exception is to catch exceptional condition that may arise at runtime but you shouldn't code to generate exception to make that decision.
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