Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive are Exceptions [duplicate]

Tags:

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?

like image 948
Kai Huppmann Avatar asked Feb 19 '09 22:02

Kai Huppmann


People also ask

Are exceptions expensive?

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.

Why are exceptions so expensive?

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.

Are exceptions in Python expensive?

In Python 3.11, “Zero-cost” exceptions are implemented. The cost of try statements is almost eliminated when no exception is raised.

How expensive is try catch?

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.


1 Answers

Exceptions are not free... so they are expensive :-)

The book Effective Java covers this in good detail.

  • Item 39 Use exceptions only for exceptional conditions.
  • Item 40 Use exceptions for recoverable conditions

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.

like image 53
TofuBeer Avatar answered Sep 22 '22 10:09

TofuBeer