How can I convert a stack trace to a string?

前端 未结 30 1450
再見小時候
再見小時候 2020-11-22 14:51

What is the easiest way to convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace?

30条回答
  •  臣服心动
    2020-11-22 15:11

     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);
            }
        }
    }
    

    When you run the program, the output will be something similar:

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

提交回复
热议问题