How can I convert a stack trace to a string?

前端 未结 30 1203
再見小時候
再見小時候 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:25

    The following code allows you to get the entire stackTrace with a String format, without using APIs like log4J or even java.util.Logger:

    catch (Exception e) {
        StackTraceElement[] stack = e.getStackTrace();
        String exception = "";
        for (StackTraceElement s : stack) {
            exception = exception + s.toString() + "\n\t\t";
        }
        System.out.println(exception);
        // then you can send the exception string to a external file.
    }
    

提交回复
热议问题