将Throwable.getStackTrace()的结果转换为描述堆栈跟踪的字符串最简单的方法是什么?


当前回答

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

public class PrintStackTrace {

    public static void main(String[] args) {

        try {
            int division = 0 / 0;
        } catch (ArithmeticException e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String exceptionAsString = sw.toString();
            System.out.println(exceptionAsString);
        }
    }
}

运行程序时,输出将类似:

java.lang.ArithmeticException: / by zero
at PrintStackTrace.main(PrintStackTrace.java:9)

其他回答

可以使用以下方法将异常堆栈跟踪转换为字符串。该类在Apache commons-lang中可用,这是许多流行开源中最常见的依赖库

org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(可丢弃)

对Gala的回答进行了详细分析,其中还将包括例外情况的原因:

private String extrapolateStackTrace(Exception ex) {
    Throwable e = ex;
    String trace = e.toString() + "\n";
    for (StackTraceElement e1 : e.getStackTrace()) {
        trace += "\t at " + e1.toString() + "\n";
    }
    while (e.getCause() != null) {
        e = e.getCause();
        trace += "Cause by: " + e.toString() + "\n";
        for (StackTraceElement e1 : e.getStackTrace()) {
            trace += "\t at " + e1.toString() + "\n";
        }
    }
    return trace;
}

如果你是为Android开发的,一个更简单的方法是使用这个:

import android.util.Log;

String stackTrace = Log.getStackTraceString(exception); 

格式与getStacktrace相同,例如。

09-24 16:09:07.042:I/System.out(4844):java.lang.NullPointerException09-24 16:09:07.042:I/System.out(4844):在com.temp.ttscancel.MainActivity.onCreate(MainActivity.java:43)09-24 16:09:07.042:I/System.out(4844):在android.app.Activity.performCreate(Activity.java:5248)09-24 16:09:07.043:I/System.out(4844):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)09-24 16:09:07.043:I/System.out(4844):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)09-24 16:09:07.043:I/System.out(4844):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)09-24 16:09:07.043:I/System.out(4844):在android.app.ActivityThread.access$800(ActivityThread.java:139)09-24 16:09:07.043:I/System.out(4844):在android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)09-24 16:09:07.043:I/System.out(4844):在android.os.Handler.dispatchMessage(Handler.java:102)09-24 16:09:07.043:I/System.out(4844):在android.os.Looper.lop(Looper.java:136)09-24 16:09:07.044:I/System.out(4844):在android.app.ActivityThread.main(ActivityThread.java:5097)09-24 16:09:07.044:I/System.out(4844):在java.lang.reflect.Method.invokeNative(本机方法)09-24 16:09:07.044:I/System.out(4844):在java.lang.reflect.Method.invoke(Method.java:515)09-24 16:09:07.044:I/System.out(4844):在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)09-24 16:09:07.044:I/System.out(4844):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)

如果你不想使用外部库,而且你不是为Android开发的,你可以创建这样的“扩展”方法:

public static String getStackTraceString(Throwable e) {
    return getStackTraceString(e, "");
}

private static String getStackTraceString(Throwable e, String indent) {
    StringBuilder sb = new StringBuilder();
    sb.append(e.toString());
    sb.append("\n");

    StackTraceElement[] stack = e.getStackTrace();
    if (stack != null) {
        for (StackTraceElement stackTraceElement : stack) {
            sb.append(indent);
            sb.append("\tat ");
            sb.append(stackTraceElement.toString());
            sb.append("\n");
        }
    }

    Throwable[] suppressedExceptions = e.getSuppressed();
    // Print suppressed exceptions indented one level deeper.
    if (suppressedExceptions != null) {
        for (Throwable throwable : suppressedExceptions) {
            sb.append(indent);
            sb.append("\tSuppressed: ");
            sb.append(getStackTraceString(throwable, indent + "\t"));
        }
    }

    Throwable cause = e.getCause();
    if (cause != null) {
        sb.append(indent);
        sb.append("Caused by: ");
        sb.append(getStackTraceString(cause, indent));
    }

    return sb.toString();
}

我的oneliner将堆栈跟踪转换为封闭的多行字符串:

Stream.of(e.getStackTrace()).map((a) -> a.toString()).collect(Collectors.joining("\n", "[", "]"))

易于传递给记录器“原样”。