投掷通用异常不鼓励? [英] Throwing generic Exception discouraged?
问题描述
为什么不鼓励抛出一个泛型(java.lang.Exception)异常,当它通常足以处理方法中的大多数条件故障?我明白如果一个方法可以抛出多种类型的异常,那么抛出异常的特定子类可能会对处理有一点澄清,但是在一般的失败/成功案例中,我认为异常的服务就足够了。
Why is it discouraged to throw a generic (java.lang.Exception) exception, when it is usually sufficient to handle most conditional failures within a method? I understand that if a method could throw multiple types of exceptions then throwing specific subclasses of an exception might clarify the handling a bit, but in a general fail/succeed case I think Exception serves more than adequate.
推荐答案
问题是异常
也是 RuntimeException $的超类c $ c>,其中包含一些不应被捕获的东西,因为它表示编程的问题,而不是由上下文引起的异常情况。在正常情况下,您不想捕获BufferOverflowException或UnsupportedOperationException。另外,抛出单独的异常类型可以调用代码来控制如何处理每个异常类型。新的多重捕获功能在Java 7中减少了锅炉。
The problem is that Exception
is also the superclass of RuntimeException
, which encompasses some stuff that shouldn't be caught as it indicates a problem with the programming rather than an exceptional condition that arises from context. You don't want to catch a BufferOverflowException or UnsupportedOperationException under normal circumstances. Besides, throwing separate Exception types gives the calling code control over how to handle each one. Boilerplate is reduced in Java 7 with the new multi-catch feature.
这篇关于投掷通用异常不鼓励?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!