Skip to main content
Error Code Decoders & Troubleshooting

Java Print Stack Trace — Complete CLI Reference, Syntax

java print stack trace is the process of outputting the call stack of an exception or current thread for debugging in Java. It is achieved via Throwable.printStackTrace(), Thread.currentThread().getStackTrace(), or the jstack CLI utility.

Syntax

# Throwable.printStackTrace() variants
public void printStackTrace()
public void printStackTrace(PrintStream s)
public void printStackTrace(PrintWriter s)

# Get stack trace as array
StackTraceElement[] elements = Thread.currentThread().getStackTrace();

# jstack CLI (JVM process)
jstack [-l] <pid>
jstack -F [-m] [-l] <pid>
jstack [-m] [-l] <executable> <core>
jstack [-m] [-l] [server_id@]<remote hostname>

Options and Flags

Flag/Variant Type Default Description
printStackTrace() Method N/A Prints exception stack trace to System.err (standard error).
printStackTrace(PrintStream s) Method N/A Writes stack trace to the specified PrintStream (e.g., System.out).
printStackTrace(PrintWriter s) Method N/A Writes stack trace to the specified PrintWriter (useful for logging).
jstack -l CLI flag N/A Long listing: prints additional information about locks.
jstack -F CLI flag N/A Force stack dump; use when target process is hung or not responding.
jstack -m CLI flag N/A Prints mixed mode stack trace (native and Java frames).

Usage Examples

1. Basic Exception Debugging with printStackTrace()

# Java code (in file DebugExample.java)
public class DebugExample {
    public static void main(String[] args) {
        try {
            int[] arr = new int[2];
            arr[5] = 10; // ArrayIndexOutOfBoundsException
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
# Compile and run
javac DebugExample.java
java DebugExample

The printStackTrace() method prints the exception class, message, and a full call stack to System.err. This is the most direct way to diagnose unhandled exceptions during development.

See also  Windows Event ID 10010 DCOM Timeout Error: Fixes & Commands

2. Capturing Stack Trace as a String for Logging

# Java code snippet
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String stackTrace = sw.toString();
System.out.println("Error:n" + stackTrace);

Using printStackTrace(PrintWriter) together with StringWriter converts the stack trace into a string. This is the standard approach for inserting stack traces into log files, databases, or custom error reports without losing context.

3. Using jstack to Debug a Hung JVM Process

# Find the Java process PID
ps aux | grep java
# Force a thread dump (use -F if process is not responding)
jstack -F <pid> > /tmp/threaddump_$(date +%Y%m%d).txt
# For a live process, use -l to see lock info
jstack -l <pid>

jstack prints Java thread stacks of a running JVM. The -F flag is critical when the process is hung and does not respond normally. The output helps identify deadlocks, blocked threads, and high‑CPU threads.

Frequently Asked Questions

What is the difference between e.printStackTrace() and Thread.currentThread().getStackTrace()?

Answer: e.

Use printStackTrace() only for rapid debugging in development. For production, prefer getStackTrace() combined with a logging framework to control output destinations and formats. Example:

Thread.currentThread().getStackTrace(); // returns StackTraceElement[]

When should I use the -XX:-OmitStackTraceInFastThrow flag?

Answer: Use -XX:-OmitStackTraceInFastThrow when recurring NullPointerException or ArrayIndexOutOfBoundsException are logged without stack traces.

JVM by default skips full stack traces after the same exception repeats ~100 times to optimize performance. Disable it with:

java -XX:-OmitStackTraceInFastThrow -jar app.jar

This forces every throw to include a full trace, critical for debugging intermittent null bugs.

How do I fix “java.lang.NullPointerException: null” with no stack trace?

Answer: Add JVM flag -XX:-OmitStackTraceInFastThrow to force full stack trace on every NullPointerException occurrence.

The message “null” without stack trace is the result of JVM optimization. For a persistent fix, also consider catching the exception early or increasing the threshold:

java -XX:-OmitStackTraceInFastThrow -jar myapp.jar

Restart the JVM after adding the flag.

See also  Vim Quit No Save: Syntax, Examples, and Error Resolution

Does -XX:-OmitStackTraceInFastThrow work on all JDK versions?

Answer: Yes, on Oracle JDK 6+, OpenJDK 6+, and most HotSpot-based JVMs.

Verify compatibility by running:

java -XX:-OmitStackTraceInFastThrow -version

If the JVM exits with “Unrecognized VM option”, the flag is unsupported. On supported JVMs, it is universally recognized across major versions (6–21+).

What is the fastest way to capture a full stack trace from a running JVM without restarting?

Answer: Use jstack (JDK 5+) or jcmd Thread.

Both tools are non-invasive and require no prior JVM flags. Example:

jstack -l 12345 | grep -A 30 "main"   # thread-specific

For production, use jcmd for richer output:

jcmd 12345 Thread.print -l

These are the fastest methods; no native agent or restart needed.