集册 Java实例教程 堆栈展开并从异常对象获取数据。

堆栈展开并从异常对象获取数据。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

583
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
堆栈展开并从异常对象获取数据。

public class Main 
/*
 from n o w j a v a . c o m - 时代Java 
*/

{

   public static void main(String[] args)

   {

      try 

      { 

         method1(); 

      }

      catch (Exception exception) // catch exception thrown in method1

      { 

         System.err.printf("%s%n%n", exception.getMessage());

         exception.printStackTrace(); /**来 自 nowjava - 时代Java**/


         // obtain the stack-trace information

         StackTraceElement[] traceElements = exception.getStackTrace();

         

         System.out.printf("%nStack trace from getStackTrace:%n");

         System.out.println("Class\t\tFile\t\t\tLine\tMethod");


         // loop through traceElements to get exception description

         for (StackTraceElement element : traceElements) 

         {

            System.out.printf("%s\t", element.getClassName());

            System.out.printf("%s\t", element.getFileName());

            System.out.printf("%s\t", element.getLineNumber());

            System.out.printf("%s%n", element.getMethodName());

         } 

      } 

   } 


   // call method2; throw exceptions back to main

   public static void method1() throws Exception

   {

      method2();

   } 


   // call method3; throw exceptions back to method1

   public static void method2() throws Exception

   {

      method3();

   }
展开阅读全文