# Java - `StackTrace`到`String`的转换

> 原文： [https://beginnersbook.com/2015/05/java-stacktrace-to-string-conversion/](https://beginnersbook.com/2015/05/java-stacktrace-to-string-conversion/)

有时我们想**将发生的异常转换为`String`**。在下面的程序中，我们使用`Throwable.printStackTrace(PrintWriter pw)`将`stacktrace`转换为`String`。

## 示例：将`Exception StackTrace`转换为`String`

```java
package com.beginnersbook.string;
import java.io.PrintWriter;
import java.io.StringWriter;

public class StacktraceToString {
    public static void main(String args[]){
        try{
            int i =5/0;
            System.out.println(i);
        }catch(ArithmeticException e){
            /* This block of code would convert the
             * stacktrace to string by using
             * Throwable.printStackTrace(PrintWriter pw)
             * which sends the stacktrace to the writer
             * that we can convert to string using tostring()
             */
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            String stacktraceString = sw.toString();
            System.out.println("String is: "+stacktraceString);
        }
    }
}

```

**输出：**

```java
String is: java.lang.ArithmeticException: / by zero
at com.beginnersbook.string.StacktraceToString.main(StacktraceToString.java:8)

```