什么时候应该使用 Throwable 而不是 new Exception?

发布于 2024-07-12 04:44:20 字数 496 浏览 11 评论 0原文

给定: ThrowableException 的超类。

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

我的问题是,什么时候应该使用 Throwable 以及什么时候应该使用 new Exception()

catchelse 块内使用:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

鲜血染红嫁衣 2024-07-19 04:44:20

始终抛出Exception(绝不是Throwable)。 通常,您也不会捕获 Throwable,但您可以捕获。 Throwable 是 ExceptionError 的超类,因此如果您不仅想捕获 Exception,那么您应该捕获 Throwable但是错误,这就是拥有它的意义。 问题是,Error 通常是普通应用程序不会也不应该捕获的事情,因此只需使用 Exception ,除非您有特定原因使用 >可抛出

Always throw an Exception (never a Throwable). You generally don't catch Throwable either, but you can. Throwable is the superclass to Exception and Error, so you would catch Throwable if you wanted to not only catch Exceptions but Errors, that's the point in having it. The thing is, Errors are generally things which a normal application wouldn't and shouldn't catch, so just use Exception unless you have a specific reason to use Throwable.

今天小雨转甜 2024-07-19 04:44:20

(来自评论)提出这个问题的是
我需要将“例外”传递给
同事正在构建的一段代码
如果集合未构建。

在这种情况下,您可能想抛出一个检查异常。 您可以抛出 Exception< /a>,它的适当的现有子类(除了 < code>RuntimeException 及其未选中的子类),或 Exception 的自定义子类(例如“CollectionBuildException ”)。 请参阅Java 异常教程以加快速度但 Java 例外。

(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.

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.

天冷不及心凉 2024-07-19 04:44:20

您不应该真正捕获异常并抛出一个像“new Exception”一样通用的新异常。

相反,如果您希望冒泡异常,只需执行以下操作:

try {
    // Do some stuff here
}
catch (DivideByZeroException e) {
    System.out.println("Can't divide by Zero!"); 
} 
catch (IndexOutOfRangeException e) { 
    // catch the exception 
    System.out.println("No matching element found.");
}
catch (Throwable e) {
    throw e; // rethrow the exception/error that occurred
}

我认为,捕获异常并抛出一个新的异常而不是引发到代码块的异常不是一个好的做法,除非您引发了一个有用的异常。自定义异常,提供足够的上下文来逃避原始异常的原因。

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:

try {
    // Do some stuff here
}
catch (DivideByZeroException e) {
    System.out.println("Can't divide by Zero!"); 
} 
catch (IndexOutOfRangeException e) { 
    // catch the exception 
    System.out.println("No matching element found.");
}
catch (Throwable e) {
    throw e; // rethrow the exception/error that occurred
}

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.

樱花坊 2024-07-19 04:44:20

在代码中只有两个地方您应该看到 Throwable 一词:

public static void main(String args[])
{
     try
     {
         // Do some stuff
     }
     catch(Throwable t)
     {

     }
 }

AND

public class SomeServlet extends HttpServlet
{
      public void doPost(HttpRequest request, HttpResponse response)
      {
         try
         {
             // Do some stuff
         }
         catch (Throwable t)
         {
              // Log
         }
      }
 }

Only two places you should see the word Throwable in code:

public static void main(String args[])
{
     try
     {
         // Do some stuff
     }
     catch(Throwable t)
     {

     }
 }

AND

public class SomeServlet extends HttpServlet
{
      public void doPost(HttpRequest request, HttpResponse response)
      {
         try
         {
             // Do some stuff
         }
         catch (Throwable t)
         {
              // Log
         }
      }
 }
埋葬我深情 2024-07-19 04:44:20

Oracle 在其官方教程(“如何抛出异常”)中给出了答案。 。

首先,它解释了 ThrowablesErrorException 类的联合,它是两种不同的东西

Throwable =错误 + 异常

接下来,它清楚地表明错误极其罕见的情况,几乎无法恢复

当 Java 中的动态链接失败或其他硬故障时
虚拟机发生时,虚拟机抛出Error。

将 1+1 放在一起,它礼貌地得出结论,(除了简单的异常没有必要捕获其他 Throwables,因为你无法对它们做任何事情。

简单的程序通常不会捕获或抛出错误。

Oracle gives the answer in its official tutorial ("How to Throw Exceptions").

First it explains that Throwables is a union of Error and Exception classes, which are 2 different things.

Throwable = Error + Exception

Next, it makes clear that an Error is something extremely rare, that is almost impossible to recover from.

When a dynamic linking failure or other hard failure in the Java
virtual machine occurs, the virtual machine throws an Error.

And putting 1+1 together, it politely concludes, that (except for simple Exceptions) there is no point in catching other Throwables, since you can't do anything about them.

Simple programs typically do not catch or throw Errors.

草莓味的萝莉 2024-07-19 04:44:20

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.

蹲在坟头点根烟 2024-07-19 04:44:20

throw new Exception(); 是你永远不应该在 catch 块中执行的操作,但你可能必须或想要执行 throw new 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 throw new SomeException(throwable); (preserving the full stack trace) instead of throw throwable; in order to conform to the API of your method, e.g. when it declares to throw SomeException but you're calling code that might throw an IOException that you don't want to add to you method's throws clause.

The probably most common case is new RuntimeException(throwable); to avoid having a throws 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.

灯下孤影 2024-07-19 04:44:20

一般来说,您不会抛出或捕获 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.

秋心╮凉 2024-07-19 04:44:20

正如我在 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).

纸短情长 2024-07-19 04:44:20

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.

2024-07-19 04:44:20

所有异常最终都是一个问题......也说错误是错误并不意味着什么。

错误不是错误 - 它们是主机虚拟机遇到的问题,例如 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.

妄想挽回 2024-07-19 04:44:20

您也不应该使用异常作为“返回类型”...

如果您抛出的条件很常见,那么您将花费大量资源将该条件返回到调用例程。 构建异常的成本很高。

我见过一些情况,其中紧密循环抛出异常作为“负”,例如 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%.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文