views:

37

answers:

1

I want to know particular exception like NullPointerException ex is faster than Exception ex.

For example my code throws NullPointerException

try {
   ...
} catch (NullPointerException e) {
   ...
}

or

try {
   ...
} catch (Exception e) {
   ...
}

Which one is faster? I think exception system depends on flags so particular type is faster because of less control. But I wonder.

And if the answer is yes say why? Thanks.

Not: You suppose there isn't any crashes on code.

A: 

The usual caveats apply... Make sure you don't optimize prematurely. Program for clarity instead of speed. If the program is too slow, use a profiler to find the problem.

Supposing Java and no exceptions are thrown, they are equally fast. The athrow operation is never called so no lookups will be performed on the exception tables and no exception-class matching needs to be done.

If you throw an exception in a try statement with a single, specific exception handler that will match the exception then the exception table lookup will match the specific exception class marginally faster than the general Exception class because it won't climb up the class hierarchy to find the matching ancestor class. By marginally, I mean you should save fewer than 10 CPU instructions and thrown exceptions should be exceptionally rare.

If you throw a variety of exceptions and have multiple catch blocks, the situation is too complicated to say it would be faster or slower to catch a single, common ancestor-class like exception; it depends on the details.

The function findExceptionBlockInMethod in Kaffe's exception.c shows one implementation of the exception-matching code.

Leif Carlsen