Skip to content

Latest commit

 

History

History
40 lines (28 loc) · 1.33 KB

File metadata and controls

40 lines (28 loc) · 1.33 KB

Java 程序:将栈跟踪转换为字符串

原文: https://www.programiz.com/java-programming/examples/convert-stack-trace-string

在此程序中,您将学习如何在 Java 中将栈跟踪转换为字符串。

示例:将栈跟踪转换为字符串

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)

在上面的程序中,我们通过将 0 除以 0 来强制程序抛出ArithmeticException

catch块中,我们使用StringWriterPrintWriter将任何给定的输出打印到字符串中。 然后,使用异常的printStackTrace()方法打印栈跟踪,并将其写入写入器。

然后,我们只需使用toString()方法将其转换为字符串。