与 Java 中的 Exception vs Throwable 相关的开销

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2129647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:53:49  来源:igfitidea点击:

Overhead associated with Exception vs Throwable in Java

javaexceptionthrowable

提问by WhyNotHugo

I know

我知道

throw new Exception();

has a pretty large overhead, since it creates a full stackTrace, etc.
Does

有一个相当大的开销,因为它创建了一个完整的堆栈跟踪,等

throw new Throwable();

present the same problem? Is this behaviour inherited, or does throwing a Throwable has a smaller (o no) overhead?

出现同样的问题?这种行为是继承的,还是抛出 Throwable 的开销较小(o 没有)?

EDIT
From an analystpoint of view, a user inserting wrong password is an exception to the normal execution order of a program. So if I have:

编辑
分析师的角度来看,用户插入错误的密码是程序正常执行顺序的一个例外。所以如果我有:

public Session newSession() {  
  validate_user_and_password();   
}

throwing a UserNotValidException would sound correct from an analystspoint of view.
Returning nullor 0just sounds incorrect if your code has pretty good abstraction. I just wanted to know if I could actually implement this in code, or if I'd have to just leave it to theory.

分析师的角度来看,抛出 UserNotValidException 听起来是正确的。如果您的代码具有很好的抽象,
返回null0只是听起来不正确。我只是想知道我是否真的可以在代码中实现它,或者我是否不得不把它留给理论。

There's a good difference between programming-point-of-view exception and analyst-point-of-view exception.

编程观点异常和分析师观点异常之间有很大的区别。

Note: I've given a really simple and silly example, this is not quite my case.
Note 2: I know returning nullwould be the ordinary thing, but I'm required to have properly abstracted and OO code, and, personally, I see no harm in this.

注意:我给出了一个非常简单和愚蠢的例子,这不是我的情况。
注 2:我知道返回null是很平常的事情,但我需要正确抽象和 OO 代码,而且,就我个人而言,我认为这没有坏处。

采纳答案by Asaph

Throwablealso creates a stacktrace when it's created. From the java docs for Throwable:

Throwable还会在创建时创建堆栈跟踪。来自java 文档Throwable

throwable contains a snapshot of the execution stack of its thread at the time it was created.

throwable 包含其线程在创建时的执行堆栈的快照。

So in terms of overhead with regards to creating a stacktrace, there should be no difference between Exceptionand Throwable.

因此,就创建堆栈跟踪的开销而言,Exception和之间应该没有区别Throwable

If you are using exceptions for "exceptional events" (as you should be), then you shouldn't be too concerned with the overhead of a stacktrace. An exceptional event occurs rarely in running code. So Exceptions shouldn't impact the performance of normal code in any significant way.

如果您对“异常事件”使用异常(正如您应该的那样),那么您不应该太担心堆栈跟踪的开销。在运行代码中很少发生异常事件。所以异常不应该以任何显着的方式影响正常代码的性能。

回答by akuhn

Nope, you need your own subclass to avoid that effect.

不,您需要自己的子类来避免这种影响。

Exception ex = new Exception() {
    @Override public Throwable fillInStackTrace() {
        return this; // and do nothing else
    }
};

This creates an instance of exception that will not fill the stack trace (the creation of exceptions delegates to fillInStackTraceto actually fill the stack trace) and is thus cheap to create.

这会创建一个不会填充堆栈跟踪的异常实例(异常的创建委托fillInStackTrace给实际填充堆栈跟踪),因此创建起来很便宜。

回答by danben

With JIT compilation, it is actually not still the case that there is a lot of overheard to throwing an Exceptionin Java. But throwing a Throwableis not much different, since you will get a stack trace there as well.

使用 JIT 编译,实际上Exception在 Java 中抛出 an 的情况并不多见。但是抛出 aThrowable并没有太大不同,因为您也会在那里获得堆栈跟踪。

If you are interested, there is a very interesting paper called "Efficient Java exception handling in just-in-time compilation" (link). Not a light read, but quite informative.

如果你有兴趣,有一篇非常有趣的论文叫做“Efficient Java exception handling in just-in-time compiler”(链接)。读起来不轻松,但信息量很大。

回答by mangoDrunk

java.lang.Exceptionextends java.lang.Throwable, so it's the same overhead. From the Javadoc:

java.lang.Exceptionextends java.lang.Throwable,所以它是相同的开销。从Javadoc

The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.

Instances of two subclasses, Error and Exception, are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).

Throwable 类是 Java 语言中所有错误和异常的超类。只有作为此类(或其子类之一)的实例的对象才会被 Java 虚拟机抛出或可以被 Java throw 语句抛出。同样,只有此类或其子类之一可以是 catch 子句中的参数类型。

两个子类的实例,Error 和 Exception,通常用于指示发生了异常情况。通常,这些实例是在异常情况的上下文中新创建的,以便包含相关信息(例如堆栈跟踪数据)。

回答by gpampara

You should never be throwing or catching Throwable.The scope of the exception is far too great.

你永远不应该抛出或捕捉Throwable.异常的范围太大了。

As stated previously, exceptions should be used only where needed, ie: in exceptional circumstances and should be specific to the situation that spawned them. That aside, catching a Throwableimplies a host of exceptions, such as OutOfMemoryException. An error of this magnitude can not be recovered from (easily) and should not be handled by the developer.

如前所述,异常应仅在需要时使用,即:在特殊情况下,并且应特定于产生它们的情况。除此之外,捕获 aThrowable意味着许多异常,例如OutOfMemoryException. 如此严重的错误无法(轻松)恢复,不应由开发人员处理。

回答by Muhammad

Throwableis parent class of Exception. so Exception classis inherited from Throwable.

Throwable是 Exception 的父类。所以Exception class是从Throwable.

回答by YuanYe

Throwable vs. Exception

Throwable 与异常

Java Exception

Java异常

As @mangoDrunk said:"Throwable is the superclass of exception and error."

正如@mangoDrunk 所说:“Throwable 是异常和错误的超类。”

回答by dimo414

You can look at the source code of the two classes to see that Exceptiondoesn't do anything beyond expose the same constructors as Throwable. All of the meat, and hence overhead, lives in Throwable.

您可以查看这两个类的源代码,看看Exception除了公开与Throwable. 所有的肉,以及因此的开销,都存在于Throwable.

Even if Exceptiondid introduce some additional overhead it would be a clear over-optimization to use Throwableinstead. Use the right tool for the job, don't co-opt the wrong tool just because it's lighter.

即使Exception确实引入了一些额外的开销,使用它也将是明显的过度优化Throwable。为工作使用正确的工具,不要仅仅因为它更轻而选择错误的工具。