alway-july

Java异常抛出使用e.printStackTrace(),打印出抛出的异常栈踪迹,

如果你在catch中继续抛出这个异常,那么e.printStackTrace()也能跟踪到抛出异常的地方,

使用throw new RunTimeException(e.fillInStackTrace()),改变异常栈踪迹。

public class TestException {
    public static void main(String[] args) {
        TestException testException = new TestException();
        testException.testException();
    }

    public void testException()
    {
        try {
            int num  = 1/0;

        }catch (RuntimeException e)
        {    
            throw new RuntimeException(e.fillInStackTrace());
       //
throw new RuntimeException(e);
      }
  }
}

console打印

Exception in thread "main" java.lang.RuntimeException: java.lang.ArithmeticException: / by zero
    at com.jxufe.study.jsonstudy.test.TestException.testException(TestException.java:22)
    at com.jxufe.study.jsonstudy.test.TestException.main(TestException.java:11)
Caused by: java.lang.ArithmeticException: / by zero
    ... 2 more

将上面的

throw new RuntimeException(e.fillInStackTrace()); 改为   throw new RuntimeException(e);

console打印

Exception in thread "main" Disconnected from the target VM, address: \'127.0.0.1:57316\', transport: \'socket\'
java.lang.RuntimeException: java.lang.ArithmeticException: / by zero
    at com.jxufe.study.jsonstudy.test.TestException.testException(TestException.java:22)
    at com.jxufe.study.jsonstudy.test.TestException.main(TestException.java:11)
Caused by: java.lang.ArithmeticException: / by zero
    at com.jxufe.study.jsonstudy.test.TestException.testException(TestException.java:17)
    ... 1 more

跟踪到抛出异常的第17行代码 int num = 1/0;

分类:

技术点:

相关文章:

  • 2021-11-20
  • 2022-12-23
  • 2021-11-20
  • 2021-11-20
  • 2021-11-20
  • 2022-12-23
  • 2022-01-08
猜你喜欢
  • 2021-09-25
  • 2021-11-30
  • 2022-12-23
  • 2021-08-18
  • 2022-12-23
  • 2021-05-23
  • 2022-12-23
相关资源
相似解决方案