Stack Trace As String Via PrintWriter

Route printStackTrace into a StringWriter and PrintWriter to capture the whole trace as one string for log lines, assertions, and error envelopes.

JavaResilience

Code

snippet
import java.io.PrintWriter;
import java.io.StringWriter;

public class StackTraceText {

    public static void main(String[] args) {
        try {
            throw new IllegalStateException("boom in service");
        } catch (IllegalStateException failure) {
            StringWriter sink = new StringWriter();
            failure.printStackTrace(new PrintWriter(sink));
            String trace = sink.toString();

            System.out.println(trace.split("\n")[0]);
            System.out.println("has frames: " + trace.contains("StackTraceText.main"));
            System.out.println("has message: " + trace.contains("boom in service"));
        }
    }
}

What the code does

Stack Trace As String Via PrintWriter keeps everything in the class StackTraceText and the function main.

The IllegalStateException throw sits inside a try: execution reaches it unconditionally, and the surrounding handler catches it.

Caveats

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.

Applying it

Output lines are prefixed (has frames:, has message:), making each step’s effect easy to spot.

The core of the file

throw new IllegalStateException("boom in service");

Interactive Tools for This Topic

FAQ

Does the snippet validate its input?
No — the `IllegalStateException` is raised inside a `try` block: execution reaches it unconditionally, and the surrounding handler clause decides what catches it. There is no input check in the snippet.
What does Stack Trace As String Via PrintWriter print when run?
Run it as a complete program — the output lines carry labels such as `has frames:`, `has message:`.