Why can I “fake” the stack trace of an exception in Java?

后端 未结 6 828
梦如初夏
梦如初夏 2021-02-19 10:39

If I run the following test, it fails:

public class CrazyExceptions {
    private Exception exception;

    @Before
    public void setUp(){
        exception =          


        
6条回答
  •  北恋
    北恋 (楼主)
    2021-02-19 11:26

    I think the assumption is that you won't be instantiating an exception unless you are in the process of throwing it, so why pay the price to get the stack trace twice?

    It would be difficult to recreate the stack trace while throwing it, as that is just sending the object out.

    The exception should be fully setup before the throw, so part of the instantiation is to get the stack trace.

    UPDATE:

    You can call fillInStackTrace() to resolve this.

提交回复
热议问题