MBH
MBH

Reputation: 16619

Is there any performance difference between catching Exception or certain type exception ? - Java

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.

Upvotes: 2

Views: 103

Answers (1)

Gergely Bacso
Gergely Bacso

Reputation: 14651

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.

Upvotes: 9

Related Questions