Reputation: 641
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
will pop up. I tried to make a runtime exception in my application, but the text area showing the exception message looks like this:
java.lang.ClassNotFoundException: com.app.Application
However, I want my text area to show something like:
Here is some part of my code surrounded by the try
and catch
:
String ex = e.toString();
this.addText(ex);
I've tried to use e.getLocalizedMessage()
and e.getMessage()
, but neither of these work.
Upvotes: 40
Views: 86578
Reputation: 1623
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();
}
Upvotes: 3
Reputation: 43728
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();
Upvotes: 6
Reputation: 10877
if you are not using any logger(Log4j or oracle logger api) then you can use the below statement to print the full exception message
try{
// statement which you want to monitor
}catch(Exception e){
e.printStackTrace()
// OR System.err.println(e.getStackTrace());
// OR System.err.println(e);
// OR System.err.println(e.getMessage());
// OR System.err.println(e.getCause());
}
if you are using the Logger API then use the below statement
try{
// statement which you want to monitor
}catch(Exception e){
log.error(e,e);
}
Upvotes: 6
Reputation: 10239
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
Upvotes: 1
Reputation: 41935
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()
Upvotes: 88
Reputation: 3017
Try e.printStackTrace()
, it will print trace for your exception with lines mentioned
Upvotes: 1