Java Exception Stacktrace Not Printing
Solution 1
The exception might be caught and thrown somewhere before your catch block. Maybe in another class which your are calling to do the logic.
An Exception
created like new Exception(new Throwable("java.lang.NullPointerException"));
will print something like what you see.
Solution 2
this is beacause java does some code optimiziation when run in server mode (java -server)
to skip this. use -XX:-OmitStackTraceInFastThrow
in java args
see link below for details:
Solution 3
If you repeatedly throw an exception, the JVM stop filling in the stack trace. I am not sure why but it may be to reduce load on the JVM. You need to be looking at an earlier stack trace to see the details.
for (int n = 0; ; n++) {
try {
Integer i = null;
i.hashCode();
} catch (Exception e) {
if (e.getStackTrace().length == 0) {
System.out.println("No more stack trace after " + n + " thrown.");
break;
}
}
prints
No more stack trace after 20707 thrown.
Solution 4
Does anyone have any ideas about how I can capture the full stack trace to a string?
You can use the below way(StringWriter.toString()) to transfer the stack trace into a String.
StringWriter writer = new StringWriter();
e.printStackTrace( new PrintWriter(writer,true ));
System. out.println("exeption stack is :\n"+writer.toString());
Solution 5
May be you don't have an appender for console output. You consider adding one. If not, log it as LOGGER.error(ex); with log4j or SLF4J
David
Updated on October 16, 2020Comments
-
David over 3 years
I have the following code:
import org.apache.commons.lang.exception.ExceptionUtils; public void myMethod() { try { // do something } catch (Exception e) { System.out.println(ExceptionUtils.getStackTrace(e)); // prints "java.lang.NullPointerException" System.out.println(ExceptionUtils.getFullStackTrace(e)); // prints "java.lang.NullPointerException" e.printStackTrace(); // prints "java.lang.NullPointerException" } }
The output that I would like to see is a full stacktrace with line numbers and the hierarchy of classes that failed. For example,
Exception in thread "main" java.lang.NullPointerException at org.Test.myMethod(Test.java:674) at org.TestRunner.anotherMethod(TestRunner.java:505) at java.util.ArrayList(ArrayList.java:405)
This code is being run inside a larger app which also has log4j, but I'm hoping to be able to get the exception into a string so I can send it as an email to the java developers.
Does anyone have any ideas about how I can capture the full stack trace to a string? I can't use Thread.currentThread().getStackTrace() since this app runs on Java 4. What might be blocking the above code from printing the full stacktrace?