Is it cheaper to catch a specific exception than a generic exception?
Let’s say I’m loading bitmaps onto my Android device. Many possible exceptions can be thrown. For simplicity, let’s take NullPointerException
and OutOfMemoryError
as examples.
Now I have two pieces of code.
Code 1
try{
load the bitmap
}
catch(Exception e)
{
do something
}
Code 2
try{
load the bitmap
catch (NullPointerException e)
{
do something
}
catch(OutOfMemoryError e)
{
do something else
}
Is one piece of code more efficient than another in terms of performance? If yes, why?
Solution
From a bytecode perspective, the first one is more efficient (less code).
But you should never look at performance that way.
If you have the same behavior for all types of exceptions, you should use the first set of code, in any other way, the second set.
In bytecode, you have the following code responsible for catching exceptions:
L2
LINENUMBER 7 L2
FRAME SAME1 java/lang/NullPointerException
ASTORE 1
GOTO L4
L3
LINENUMBER 9 L3
FRAME SAME1 java/lang/Exception
ASTORE 1
L4
So every exception has a code responsible for catching it, but as I said, this is a small difference and it shouldn’t be considered.