Stack trace as String

后端 未结 7 1282
梦谈多话
梦谈多话 2020-12-23 20:18

How do I get full exception message in Java?

I am creating a Java Application. If there is a runtime exception, a JDialog with a JTextArea

相关标签:
7条回答
  • 2020-12-23 20:47

    Try e.printStackTrace(), it will print trace for your exception with lines mentioned

    0 讨论(0)
  • 2020-12-23 20:48

    To get the stack trace into a string you can use these lines:

        CharArrayWriter cw = new CharArrayWriter();
        PrintWriter w = new PrintWriter(cw);
        e.printStackTrace(w);
        w.close();
        String trace = cw.toString();
    
    0 讨论(0)
  • 2020-12-23 20:49

    e.printStackTrace will give the full stack trace

    0 讨论(0)
  • 2020-12-23 20:50

    This is the full exception message.

    If you want more information try e.printStackTrace()

    then you will get excatly what you see on the picture you postet

    0 讨论(0)
  • 2020-12-23 20:55

    You need to call the Throwable#printStackTrace(PrintWriter);

    try{
    
    }catch(Exception ex){
        String message = getStackTrace(ex);
    }
    
    public static String getStackTrace(final Throwable throwable) {
         final StringWriter sw = new StringWriter();
         final PrintWriter pw = new PrintWriter(sw, true);
         throwable.printStackTrace(pw);
         return sw.getBuffer().toString();
    }
    

    You can also use commons-lang-2.2.jar Apache Commons Lang library which provides this functionality:

    public static String getStackTrace(Throwable throwable)
    Gets the stack trace from a Throwable as a String.
    

    ExceptionUtils#getStackTrace()

    0 讨论(0)
  • 2020-12-23 21:00
    public static String getStackMsg(Throwable e) {
        StringBuffer sb = new StringBuffer();
        sb.append(e.toString()).append("\n");
        StackTraceElement[] stackArray = e.getStackTrace();
    
        for(int i = 0; i < stackArray.length; ++i) {
            StackTraceElement element = stackArray[i];
            sb.append(element.toString() + "\n");
        }
    
        return sb.toString();
    }
    
    0 讨论(0)
提交回复
热议问题