Why is Throwable.fillInStackTrace() method public? Why would someone use it?

后端 未结 6 771
不思量自难忘°
不思量自难忘° 2020-12-13 07:12

I\'m curious why is method fillInStackTrace of java.lang.Throwable public?

This method replaces original stack trace with that from the pl

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 07:34

    Perhaps you want to catch an exception and throw a new one that does not encapsulate your previous exception. getStackTrace from the caught one, and set the stackTrace for the new one.

    This would also work when you have a singleton exception, instantiated once like:

    private static Exception theException = new MyException();
    

    that is thrown multiple times. This would set the stackTrack to something related to the caught exception without the need to expensively create a new exception every time. I think this is how Scala does its continue and break constructs.

    try {
        ....
    } catch (OtherException oe) {
        theException.fillStackTrace(oe.getStackTrace());
        theException.setMessage(...); //etc
        throw theException;
    }
    

    Using static exceptions can be tricky if it can be thrown multiple times concurrently (i.e. in threads)

提交回复
热议问题