Search code examples
javaprintingerror-handlingstack-tracejoptionpane

Printing stack trace in JOptionPane


My question: How can i put the text e.printStackTrace prints into a JOptionPane window

My code is currently as follows:
excuse the poor formatting :P

try {
  //SOME CODE
} catch (Exception e) {
  e.printStackTrace();
  JOptionPane.showMessageDialog(null,
     "An unexpected error has occurred:\n" + e.getMessage() + '\n' + Thread.currentThread().getStackTrace() +  "\nPlease send this error to ." + email + "\nThanks for your help.",
     "Error", JOptionPane.ERROR_MESSAGE);
}

this both prints the stack trace in the command line interface(i am using terminal) and it creates a JOptionPane but NOT with the same info as e.printStackTrace(). when running my program from a jar file, the command line interface won't be visible so the user will only get the JOptionPane window which doesnt have all of the info i need to succesfully identify the problem

Thanks in advance :)


Solution

  • Here, This is just some general code I came up with that will get you the same output as e.printStackTrace().

    try {
        // some code
    } catch (Exception e) {
        StringBuilder sb = new StringBuilder(e.toString());
        for (StackTraceElement ste : e.getStackTrace()) {
            sb.append("\n\tat ");
            sb.append(ste);
        }
        String trace = sb.toString();
        // Now, trace contains the stack trace
        // (However, you can only use it inside the catch block)
    }
    

    However, as was previously mentioned, you probably want a window in which you can scroll, as I don't think it'd fit very well in a JOptionPane.