打印全部异常堆栈、ExceptionUtils.getFullStackTrace这样最快

简介: 打印全部异常堆栈、ExceptionUtils.getFullStackTrace这样最快

//打印全部异常堆栈
public class ExceptionUtils {
  public static void main(String[] args) {
    try {
      int a=1/0;
    } catch (Exception e) {
      e.printStackTrace();
      String fullStackTrace = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e);
      System.out.println(fullStackTrace);
    }
  }
}
 /**
     * <p>A way to get the entire nested stack-trace of an throwable.</p>
     *
     * <p>The result of this method is highly dependent on the JDK version
     * and whether the exceptions override printStackTrace or not.</p>
     *
     * @param throwable  the <code>Throwable</code> to be examined
     * @return the nested stack trace, with the root cause first
     * @since 2.0
     */
    public static String getFullStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        Throwable[] ts = getThrowables(throwable);
        for (int i = 0; i < ts.length; i++) {
            ts[i].printStackTrace(pw);
            if (isNestedThrowable(ts[i])) {
                break;
            }
        }
        return sw.getBuffer().toString();
    }
//另一种方式
public static String exception2String(Exception ex){
    String exceptionMessage = "";
    if (ex != null) {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      try {
        ex.printStackTrace(pw);
        exceptionMessage = sw.toString();
      } finally {
        try {
          sw.close();
          pw.close(); 
        } catch (Exception e) {
        }
      }
    }
    return exceptionMessage;
  }
目录
相关文章
|
3月前
|
Java
如何使用 try-catch 块来捕获静态变量初始化中的异常
在Java中,可以通过在静态初始化块或静态变量初始化时使用try-catch语句来捕获可能出现的异常,确保程序的健壯性。具体做法是在静态初始化代码中加入try-catch结构,对可能抛出的异常进行处理。
113 16
|
4月前
|
监控 Java
捕获线程执行异常的多种方法
【10月更文挑战第15天】捕获线程执行异常的方法多种多样,每种方法都有其特点和适用场景。在实际开发中,需要根据具体情况选择合适的方法或结合多种方法来实现全面有效的线程异常捕获。这有助于提高程序的健壮性和稳定性,减少因线程异常带来的潜在风险。
53 1
|
5月前
|
Java
日志框架log4j打印异常堆栈信息携带traceId,方便接口异常排查
日常项目运行日志,异常栈打印是不带traceId,导致排查问题查找异常栈很麻烦。
|
5月前
|
Python
自定义异常堆栈信息
自定义异常堆栈信息
66 0
|
7月前
|
运维
系统日志使用问题之如何防止在打印参数时遇到NPE(空指针异常)
系统日志使用问题之如何防止在打印参数时遇到NPE(空指针异常)
|
9月前
|
Linux
使用backtrace打印程序crash堆栈
使用backtrace打印程序crash堆栈
130 0
|
Java
强制要求JVM始终抛出含堆栈的异常(-XX:-OmitStackTraceInFastThrow)
强制要求JVM始终抛出含堆栈的异常(-XX:-OmitStackTraceInFastThrow)
204 0
Logger.error方法之打印错误异常的详细堆栈信息
Logger.error方法之打印错误异常的详细堆栈信息
765 0
【异常机制】使用异常打印错误信息
【异常机制】使用异常打印错误信息
124 0
【异常机制】使用异常打印错误信息
有关异常的处理、捕获、抛出、自定义
有关异常的处理、捕获、抛出、自定义
123 0