Which part of throwing an Exception is expensive?

后端 未结 6 2033
盖世英雄少女心
盖世英雄少女心 2020-11-30 16:52

In Java, using throw/catch as a part of logic when there\'s not actually an error is generally a bad idea (in part) because throwing and catching an exception is expensive,

6条回答
  •  清歌不尽
    2020-11-30 17:09

    The first operation in most Throwable constructors is to fill in the stack trace, which is where most of the expense is.

    There is, however, a protected constructor with a flag to disable the stack trace. This constructor is accessible when extending Exception as well. If you create a custom exception type, you can avoid the stack trace creation and get better performance at the expense of less information.

    If you create a single exception of any type by normal means, you can re-throw it many times without the overhead of filling in the stack trace. However, its stack trace will reflect where it was constructed, not where it was thrown in a particular instance.

    Current versions of Java make some attempts to optimize stack trace creation. Native code is invoked to fill in the stack trace, which records the trace in a lighter-weight, native structure. Corresponding Java StackTraceElement objects are lazily created from this record only when the getStackTrace(), printStackTrace(), or other methods that require the trace are called.

    If you eliminate stack trace generation, the other main cost is unwinding the stack between the throw and the catch. The fewer intervening frames encountered before the exception is caught, the faster this will be.

    Design your program so that exceptions are thrown only in truly exceptional cases, and optimizations like these are hard to justify.

提交回复
热议问题