示例: 将堆栈跟踪转换为字符串
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
块中,我们使用
StringWriter
和
PrintWriter
将任何给定的输出打印为字符串。然后我们使用异常的
printStackTrace()
方法打印堆栈跟踪并将其写入 writer。
然后,我们只需使用
toString()
方法将其转换为字符串。