什么时候应该使用Throwable而不是新的Exception? [英] When should Throwable be used instead of new Exception?

查看:196
本文介绍了什么时候应该使用Throwable而不是新的Exception?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于: Throwable Exception 的超类。

当我阅读关于编写自己的例外的文本时,我看到在 catch Throwable 的示例>块和其他文本显示 catch 块中使用的新Exception()。我还没有看到何时应该使用每个的解释。

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.

我的问题是这个,什么时候应该 Throwable 是否应该使用使用新的Exception()

My question is this, when should Throwable be used and when should new Exception() be used?

catch else 阻止使用:

throw throwable;

throw new Exception();


推荐答案


(来自评论)带来这个问题的问题是
我需要将一个'例外'传递给一个
的代码,如果一个集合没有建成,那么同事正在构建

(from comments) The issue that brought this up is that I need to pass an 'exception' to a piece of code a coworker is building if a collection does not get built.

在这种情况下,您可能希望抛出已检查的异常。您可以抛出 异常 ,它的适当现有子类( RuntimeException 及其未选中的子类),或的自定义子类异常(例如 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 (except RuntimeException and its subclasses which are unchecked), or a custom subclass of Exception (e.g. "CollectionBuildException"). See the Java Tutorial on Exceptions to get up to speed with Java exceptions.

这篇关于什么时候应该使用Throwable而不是新的Exception?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆