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

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

问题描述

给定:ThrowableException 的超类.

Given: Throwable is Exception's superclass.

当我阅读有关编写自己的异常"的文本时,我看到 Throwablecatch 块中使用的示例,其他文本显示 new Exception()catch 块中使用.我还没有看到什么时候应该使用每一个的解释.

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,什么时候应该使用new Exception()?

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

catchelse 块内使用:

Inside the catch or else block using either:

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.

在这种情况下,您可能想要抛出一个检查异常.你可以抛出一个 Exception,它的一个适当的现有子类(除了 RuntimeException 及其 unchecked 的子类,或 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 (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 而不是 new Exception?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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