Overhead associated with Exception vs Throwable in Java

前端 未结 8 819
一个人的身影
一个人的身影 2020-12-05 06:53

I know

throw new Exception();

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

throw new Thr         


        
相关标签:
8条回答
  • 2020-12-05 07:31

    java.lang.Exception extends java.lang.Throwable, so it's the same overhead. From the 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).

    0 讨论(0)
  • 2020-12-05 07:32

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

    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.

    0 讨论(0)
  • 2020-12-05 07:32

    Throwable is parent class of Exception. so Exception class is inherited from Throwable.

    0 讨论(0)
  • 2020-12-05 07:32

    Throwable vs. Exception

    Java Exception

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

    0 讨论(0)
  • 2020-12-05 07:32

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

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

    0 讨论(0)
  • 2020-12-05 07:34

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

    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 Throwable implies 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.

    0 讨论(0)
提交回复
热议问题