打印Java异常堆栈信息

时间:2023-03-09 04:30:01
打印Java异常堆栈信息

背景

在开发Java应用程序的时候,遇到程序抛异常,我们通常会把抛异常时的运行时环境保存下来(写到日志文件或者在控制台中打印出来)。这样方便后续定位问题。

需要记录的运行时环境包含两部分内容:抛异常时的参数信息和函数调用堆栈。针对堆栈信息,如果直接调用Exception的getStackTrace方法获取将得到这样一句没用的信息:

 [Ljava.lang.StackTraceElement;@4361bd48

我们希望能打印完整的调用堆栈,像这样:

 com.elon.FileNoExistException at com.elon.StaruptService.throwException(StaruptService.java:21)
 at com.elon.StaruptService.main(StaruptService.java:9)

方案

提供一个静态公有方法用于获取异常的堆栈信息。将堆栈作为异常信息的一部分输出到日志文件或者打印到控制台界面。

步骤一:创建一个Demo项目

打印Java异常堆栈信息

步骤二:编写样例代码

1、获取异常堆栈的公共方法:

 package com.elon;

 import java.io.PrintWriter;
 import java.io.StringWriter;

 public class UtilTool
 {
     /**
      * 获取异常的调用堆栈信息。
      *
      * @return 调用堆栈
      */
     public static String toStackTrace(Exception e)
     {
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);

         try
         {
             e.printStackTrace(pw);
             return sw.toString();
         }
         catch(Exception e1)
         {
             return "";
         }
     }
 }

2、增加一个判断文件不存在时抛出的异常:

 package com.elon;

 /**
  * 自定义的文件不存在异常。
  *
  * @author elon
  */
 public class FileNoExistException extends Exception
 {
     private static final long serialVersionUID = 7929453457697405891L;

     /**
      * 文件完整路径
      */
     private String filePath;

     /**
      * 构造函数。初始化文件路径。
      *
      * @param filePath 文件路径
      */
     public FileNoExistException(String filePath)
     {
         this.filePath = filePath;
     }

     public String getExceptionMsg()
     {
         return "filePath:" + filePath + "|exception trace:" + UtilTool.toStackTrace(this);
     }
 }

3、打印异常信息:

 public class StaruptService
 {
     public static void main(String[] args)
     {
         try
         {
             FileNoExistException e = throwException();
         }
         catch (FileNoExistException e)
         {
             System.out.println(e.getExceptionMsg());
         }
     }

     private static FileNoExistException throwException() throws FileNoExistException
     {
         throw new FileNoExistException("D:/123.xlsx");
     }
 } 

测试打印结果

 filePath:D:/123.xlsx|exception trace:com.elon.FileNoExistException at com.elon.StaruptService.throwException(StaruptService.java:19)
 at com.elon.StaruptService.main(StaruptService.java:9)