什么时候应该使用 Throwable 而不是 new Exception?
给定:Throwable
是 Exception
的超类.
Given: Throwable
is Exception
's superclass.
当我阅读有关编写自己的异常"的文本时,我看到 Throwable
在 catch
块中使用的示例,其他文本显示 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?
在 catch
或 else
块内使用:
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.