Overhead associated with Exception vs Throwable in Java

前端 未结 8 820
一个人的身影
一个人的身影 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:39

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

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

    So in terms of overhead with regards to creating a stacktrace, there should be no difference between Exception and 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.

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

    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 fillInStackTrace to actually fill the stack trace) and is thus cheap to create.

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