简体   繁体   English

捕获特定异常比捕获通用异常更便宜吗?

[英]Is catching a specific exception less expensive than catching a generic one?

Say I'm loading a Bitmap onto my Android device. 假设我正在将一个位图加载到我的Android设备上。 There are many possible exceptions that can be thrown. 可以抛出许多可能的异常。 For the sake of simplicity let's take NullPointerException and OutOfMemoryError . 为简单起见,我们采用NullPointerExceptionOutOfMemoryError

Now I have two pieces of code. 现在我有两段代码。

Code 1 代码1

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

Code 2 代码2

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 performance 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: 在字节代码中,您有以下代码负责捕获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. 性能方面没有区别,因为即使在多个catch块的情况下也只会执行一个catch。

Code wise, yes first one is better as Michal said. 代码明智,是首先一个更好,因为Michal说。 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. 表演将是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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