java 异常堆栈输出_打印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項目
步驟二:編寫樣例代碼
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)
總結
以上是生活随笔為你收集整理的java 异常堆栈输出_打印Java异常堆栈信息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux java字符集编码_Java
- 下一篇: java学习笔记-良葛格_Java良葛格