2

I wonder whether can be a difference or performance issues between those 2 blocks:

 try{ return Integer.parseInt(numAsString); }catch (Exception e){ return onErrorInt; } 

and

 try{ return Integer.parseInt(numAsString); }catch (NumberFormatException e){ return onErrorInt; } 

Sometimes there is even inside the try many kind of exceptions like:

 try{ // open file then try to close // try to parse integer // another kind of exception throwing funcitons }catch (Exception e){ return onErrorInt; } 

and

 try{ // open file then try to close // try to parse integer // another kind of exception throwing funcitons }catch (NumberFormatException e){ return // something; } catch (IOException e){ // return same thing in the exception above } 

.

What i am doing is System that will stay running 24 hours a day with 1 restart per day.

In many places i dont care about the type of the Exception, i just need to let my app running all the time. So mainly my question about performance.

7
  • When you catch a specific one you can handle it specifically? Commented Jan 18, 2016 at 8:25
  • 5
    Until you proove this piece of code is causing performance issues you should do the right thing. The question as it stands doesn't make sense. The difference if any will not be anything you will notice. Commented Jan 18, 2016 at 8:30
  • If you're worrying about performance of catching exception you're probably throwing them too often and there's something terribly wrong with your code. Commented Jan 18, 2016 at 8:30
  • 1
    IMO the performance impact to catch them specifically is incredible low (Comparable to an if). However a very noticeable amount of time/performance is needed to throw the Exceptions (generate stacktrace etc). If you need max performance, then don't throw exceptions at all. Commented Jan 18, 2016 at 8:33
  • 1
    Sometimes maybe. But that won't cause any performance issues. Of course you'll have to catch exceptions to keep the system up and running, but performance shouldn't be a problem. Commented Jan 18, 2016 at 8:34

1 Answer 1

9

Performance difference? Practically nothing. The only cost is iterating through the ExceptionTable, which is a very low profile, in-memory operation. you can read a a short summary about the internals here:

JVM spec on Exception handling

The main reason for distinguishing between exception types is to allow developers to take different actions upon different type of exceptions if it is needed.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.