[英]Java when to catch general Exceptions and specific Exceptions
I am always using catch (Exception e) {//whatever} but is that actually correct ? 我一直在使用catch(Exception e){// whatever},但这实际上是正确的吗? Why should I use specific exceptions if general Exception works for everything ?
如果通用异常适用于所有情况,为什么还要使用特定的异常? Does it somehow affect the performance ?
它会以某种方式影响性能吗?
I am always using catch (Exception e) {//whatever} but is that actually correct ?
我一直在使用catch(Exception e){// whatever},但这实际上是正确的吗?
No. That goes against good recommendation to catch the most appropriate specific exception. 否。这与捕获最适当的特定例外的良好建议背道而驰。
Why should I use specific exceptions if general Exception works for everything ?
如果通用异常适用于所有情况,为什么还要使用特定的异常?
Because exceptions you don't really expect can be masked. 因为您确实没有想到的异常可以被掩盖。 For example, when performing some database operations, a
SQLException
might happen, which is expected, and you can implement handling it gracefully. 例如,当执行某些数据库操作时,可能会发生
SQLException
,这是预料之中的,您可以实现对其的优雅处理。 And if a ArrayIndexOutOfBoundsException
gets thrown, that would be unexpected, and most probably indicate a programming error. 而且,如果抛出
ArrayIndexOutOfBoundsException
,这将是意外的,并且很可能表示编程错误。 But if instead SQLException
you catch Exception
, then you might never know that the unexpected ArrayIndexOutOfBoundsException
was thrown. 但是,如果不是
SQLException
而是捕获Exception
,那么您可能永远不会知道抛出了意外的ArrayIndexOutOfBoundsException
。 And the graceful cleanup might also not apply for this kind of exception. 优雅的清理也可能不适用于这种异常。
Using specific exceptions also makes the code more readable: the reader can understand what kind of things can go wrong in the code guarded by the try-catch
. 使用特定的异常还可以使代码更具可读性:读者可以理解
try-catch
保护的代码中可能发生什么事情。
Related to this is that when you declare a method to throw an exception, the declaration should use the exception that's most appropriate to the abstraction. 与此相关的是,当您声明引发异常的方法时,声明应使用最适合抽象的异常。
Does it somehow affect the performance ?
它会以某种方式影响性能吗?
Not at all. 一点也不。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.