Do you know how expensive exception throwing and handling in java is?
We had several discussions about the real cost of exceptions in our team. Some avoid them as often as possible, some say the loss of performance by using exceptions is overrated.
Today I found the following piece of code in our software:
private void doSomething() { try { doSomethingElse(); } catch(DidNotWorkException e) { log("A Message"); } goOn(); } private void doSomethingElse() { if(isSoAndSo()) { throw new DidNotWorkException(); } goOnAgain(); }
How is the performance of this compared to
private void doSomething() { doSomethingElse(); goOn(); } private void doSomethingElse() { if(isSoAndSo()) { log("A Message"); return; } goOnAgain(); }
I don't want to discuss code aesthetic or anything, it's just about runtime behaviour! Do you have real experiences/measurements?
Exceptions are expensive, but there is more to it when you want to choose between exception and return codes. Historically speaking the argument was: exceptions ensure that code is forced to handle the situation whereas return codes can be ignored.
So we clearly see there is an extra cost for exception handling that increases the deeper the stack trace goes. This is because when an exception is thrown the runtime needs to search up the stack until it hits a method than can handle it. The further it has to look up the stack, the more work it has to do.
In Python 3.11, “Zero-cost” exceptions are implemented. The cost of try statements is almost eliminated when no exception is raised.
try has almost no expense at all. Instead of doing the work of setting up the try at runtime, the code's metadata is structured at compile time such that when an exception is thrown, it now does a relatively expensive operation of walking up the stack and seeing if any try blocks exist that would catch this exception.
Exceptions are not free... so they are expensive :-)
The book Effective Java covers this in good detail.
The author found that exceptions resulted in the code tunning 70 times slower for his test case on his machine with his particular VM and OS combo.
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