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

后端 未结 6 830
梦如初夏
梦如初夏 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:34

    You wouldn't want throwing an exception to alter the stack track or you couldn't re-throw an exception safely.

    public void throwsException() {
        throw new RuntimeException();
    }
    
    public void logsException() {
        try {
            throwsException();
        } catch (RuntimeException e) {
            e.printStrackTrace();
            throw e; // doesn't alter the exception.
        }
    }
    
    @Test
    public void youCanSeeTheCauseOfAnException(){
        try {
            logsException();
        } catch(Exception e) {
            e.printStrackTrace(); // shows you the case of the exception, not where it was last re-thrown.
        }
    }
    

提交回复
热议问题