Java异常处理——如何跟踪异常的传播路径?

当程序中出现异常时,JVM会依据方法调用顺序依次查找有关的错误处理程序。

可使用printStackTrace getMessage方法了解异常发生的情况:

    printStackTrace:打印方法调用堆栈。

   每个Throwable类的对象都有一个getMessage方法,它返回一个字串,这个字串是在Exception构造函数中传入的,通常让这一字串包含特定异常的相关信息。

示例程序

 1 // UsingExceptions.java
 2 // Demonstrating the getMessage and printStackTrace
 3 // methods inherited into all exception classes.
 4 public class PrintExceptionStack {
 5    public static void main( String args[] )
 6    {
 7       try {
 8          method1();
 9       }
10       catch ( Exception e ) {
11          System.err.println( e.getMessage() + "
" );
12          e.printStackTrace();
13       }
14    }
15 
16    public static void method1() throws Exception
17    {
18       method2();
19    }
20 
21    public static void method2() throws Exception
22    {
23       method3();
24    }
25 
26    public static void method3() throws Exception
27    {
28       throw new Exception( "Exception thrown in method3" );
29    }
30 }

结果截图

原文地址:https://www.cnblogs.com/weipinggong/p/4962449.html