简体   繁体   中英

Is catching a specific exception less expensive than catching a generic one?

Say I'm loading a Bitmap onto my Android device. There are many possible exceptions that can be thrown. For the sake of simplicity let's take NullPointerException and OutOfMemoryError .

Now I have two pieces of code.

try{
//load the bitmap
}
catch(Exception e)
{
//do something
}

try{
//load the bitmap
catch (NullPointerException e)
{
//do something
}
catch(OutOfMemoryError e)
{
//do something else
}

Is one piece of code more effective than the other wise? 更有效吗? If so, why?

From byte code point of view it is more effective (less code) to do the first one.

But you should NEVER look at performance in that way.

If you have the same behavior for all type of exceptions, you should use the first bunch of code, in any other way, the second one.

In byte code you have following code responsible for catching eceptions:

   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 each exceptions has a code that is responsible for catching that, but as I said this is such a minor difference that it shouldn't be taken into consideration.

Performance wise there's no difference as only one catch will be executed even in case of multiple catch blocks.

Code wise, yes first one is better as Michal said. Good practice wise second approach is better as you are able to capture specific exceptions and handle them appropriately.

Side note: don't catch out of memory error ever, its an error not exception and you cant handle it effectively

if you have different behaviours for each exception the second one is better than the first.

The performances will be the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM