什么时候应该使用 Throwable 而不是 new Exception?
给定: Throwable
是 Exception
的超类。
当我阅读有关编写自己的“异常”的文本时,我看到 catch
块中使用 Throwable
的示例,其他文本显示 new Exception() 在
catch
块中使用。 我还没有看到什么时候应该使用每一种的解释。
我的问题是,什么时候应该使用 Throwable
以及什么时候应该使用 new Exception()
?
在 catch
或 else
块内使用:
throw throwable;
或
throw new Exception();
Given: Throwable
is Exception
's superclass.
When I read texts on writing your own 'exceptions', I see examples of Throwable
being used in the catch
block and other texts show new Exception()
being used in the catch
block. I have yet to see an explanation of when one should use each.
My question is this, when should Throwable
be used and when should new Exception()
be used?
Inside the catch
or else
block using either:
throw throwable;
or
throw new Exception();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
始终抛出
Exception
(绝不是Throwable
)。 通常,您也不会捕获Throwable
,但您可以捕获。 Throwable 是Exception
和Error
的超类,因此如果您不仅想捕获Exception
,那么您应该捕获Throwable
但是错误
,这就是拥有它的意义。 问题是,Error
通常是普通应用程序不会也不应该捕获的事情,因此只需使用Exception
,除非您有特定原因使用>可抛出
。Always throw an
Exception
(never aThrowable
). You generally don't catchThrowable
either, but you can. Throwable is the superclass toException
andError
, so you would catchThrowable
if you wanted to not only catchException
s butError
s, that's the point in having it. The thing is,Error
s are generally things which a normal application wouldn't and shouldn't catch, so just useException
unless you have a specific reason to useThrowable
.在这种情况下,您可能想抛出一个检查异常。 您可以抛出
Exception
< /a>,它的适当的现有子类(除了 < code>RuntimeException 及其未选中的子类),或Exception
的自定义子类(例如“CollectionBuildException
”)。 请参阅Java 异常教程以加快速度但 Java 例外。In that case, you might want to throw a checked exception. You could throw an
Exception
, an appropriate existing subclass of it (exceptRuntimeException
and its subclasses which are unchecked), or a custom subclass ofException
(e.g. "CollectionBuildException
"). See the Java Tutorial on Exceptions to get up to speed with Java exceptions.您不应该真正捕获异常并抛出一个像“new Exception”一样通用的新异常。
相反,如果您希望冒泡异常,只需执行以下操作:
我认为,捕获异常并抛出一个新的异常而不是引发到代码块的异常不是一个好的做法,除非您引发了一个有用的异常。自定义异常,提供足够的上下文来逃避原始异常的原因。
You should not really catch an exception and throw a new one as general as "new Exception".
Instead, if you wish to bubble up the exception just do the following:
It is not good practise, I believe, to catch an exception and throw a new exception instead of the one that was raised to your code block, unless you raise a useful custom exception that provides enough context to elude to the cause of the original exception.
在代码中只有两个地方您应该看到
Throwable
一词:AND
Only two places you should see the word
Throwable
in code:AND
Oracle 在其官方教程(“如何抛出异常”)中给出了答案。 。
首先,它解释了
Throwables
是Error
和Exception
类的联合,它是两种不同的东西。接下来,它清楚地表明
错误
是极其罕见的情况,几乎无法恢复 。将 1+1 放在一起,它礼貌地得出结论,(除了简单的
异常
)没有必要捕获其他Throwable
s,因为你无法对它们做任何事情。Oracle gives the answer in its official tutorial ("How to Throw Exceptions").
First it explains that
Throwables
is a union ofError
andException
classes, which are 2 different things.Next, it makes clear that an
Error
is something extremely rare, that is almost impossible to recover from.And putting 1+1 together, it politely concludes, that (except for simple
Exception
s) there is no point in catching otherThrowable
s, since you can't do anything about them.Throwable 是一个接口,而不是一个类。两个类扩展了 Throwable:Exception 和 Error。规则是:捕获异常时尽可能具体 - 这意味着例如捕获 Exception 而不是 Throwable,捕获 IOException 而不是 Exception。
不要捕获错误 - 错误就是错误。 而是修复代码。
如果您必须捕获所有内容,请使用“catch Throwable”,但这是不好的形式。
Throwable is an interface, not a class.Two classes extend Throwable, Exception and Error.The rule is: be as specific as you can when catching exceptions - that means for example catching Exception instead of Throwable, and IOException instead of Exception.
Don't catch Errors - errors are bugs. Fix the code instead.
If you have to catch absolutely everything, use "catch Throwable", but this is bad form.
throw new Exception();
是你永远不应该在 catch 块中执行的操作,但你可能必须或想要执行 thrownew SomeException( throwable); 操作。
(保留完整的堆栈跟踪)而不是throw throwable;
为了符合你的方法的 API,例如,当它声明抛出SomeException
但你正在调用可能抛出IOException
的代码,而您不想将其添加到方法的throws
子句中。最常见的情况可能是 new RuntimeException(throwable); 以避免完全使用 throws 子句。 许多人会告诉您这是一种可怕的滥用,因为您应该使用受检查的异常。 在我看来,他们是错误的,检查异常是 Java 语言设计中的一个错误,只会导致丑陋且难以维护的代码。
throw new Exception();
is something you should never do in a catch block, but you may have to or want to do thrownew SomeException(throwable);
(preserving the full stack trace) instead ofthrow throwable;
in order to conform to the API of your method, e.g. when it declares to throwSomeException
but you're calling code that might throw anIOException
that you don't want to add to you method'sthrows
clause.The probably most common case is
new RuntimeException(throwable);
to avoid having athrows
clause altogether. Many people will tell you this is a horrible abuse because you should be using checked exceptions. IMO they are wrong and checked exceptions are a mistake in the Java language design that just results in ugly, unmaintainable code.一般来说,您不会抛出或捕获 Throwable。 特别是,JVM 错误(扩展 Error() )不会被用户代码捕获,除非您正在执行奇怪的系统级工作。
将“Throwable”视为语言工件。 “Exception”类之所以如此命名,是因为程序员希望代码块“异常”退出(不正常退出或返回值)时使用它。
这包括常规错误情况(我所说的“常规”错误是指与 JVM 错误相反)以及使用异常作为控制机制的地方。
Generally, you would not throw or catch Throwable. In particular, JVM errors (that extend Error() ) are not meant to be caught by user code unless you are doing weird system-level work.
Treat "Throwable" as a language artifact. The "Exception" class is named that because it is the one that is intended to be used by programmers when they want a code block to exit "exceptionally" - by not exiting normally or returning a value.
That includes both regular error situations (by "regular" I mean as opposed to JVM errors) and places where you are using exceptions as a control mechanism.
正如我在 java 刚问世时听到的那样,理论上 Throwable 可能用于除异常之外的其他情况下的控制权转移。 但我从未见过它以这种方式使用(这可能是一件非常好的事情)。
因此,只需捕获异常(或者更好的是,捕获更细粒度的异常)。
As I heard it when java first came out, the theory was that Throwable might be used for transfer of control in other cases besides exceptions. I've never seen it used that way though (and that's probably a Very Good Thing).
So just catch Exception (or better yet, a more fine-grained exception).
Throwable 意味着只能被程序的容器或主循环捕获。 大多数情况下,捕获异常以下的内容(例如错误)不会为程序添加太多功能,毕竟如果抛出 VirtualError 或其他错误,您可以做什么。 除了记录并继续之外没有太多内容。
Throwable is meant to be only caught by the container or main loop of your program. Most of the time catching stuff below Exception eg Error does not add much capability to a program, after all what can you possible do if a VirtualError other Errors are thrown. Not much except log and continue.
所有异常最终都是一个问题......也说错误是错误并不意味着什么。
错误不是错误 - 它们是主机虚拟机遇到的问题,例如 OutOfMemoryError。 异常是当前操作可以用来通知它失败并可能提供一些诊断的一种方法。
All exceptions are a problem in the end... too say Errors are bugs doesnt mean anything.
Errors are not bugs - they are problems that the host VM is experiencing, eg OutOfMemoryError. Exceptions are a means that the current operation may use to notify that it failed and perhaps provide some diagnosis.
您也不应该使用异常作为“返回类型”...
如果您抛出的条件很常见,那么您将花费大量资源将该条件返回到调用例程。 构建异常的成本很高。
我见过一些情况,其中紧密循环抛出异常作为“负”,例如 ID 分配,这个例程占用了大约 99% 的 CPU 时间。当改为记录的返回常量时,这个值下降到 25%。
You shouldn't use Exceptions as a "return type" either...
If the condition you're throwing for is common, you are spending a huge amount of resources to return that condition to the calling routine. Exceptions are expensive to construct.
I've seen cases where tight loops that threw exceptions as a "negative" for e.g. ID allocation, this routine occupied about 99% of the CPU time .. when changed to a documented return constant instead, this dropped to 25%.