Java: Print Stack Trace as String Without Exception


If you have a use case where you want your application to terminate with an exception but rather want to catch the exception and print the stack trace as a String, below is an example to demonstrate it.

package org.code2care.java.sorting.algo;

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

public class ExceptionAsString {
    public static void main(String[] args) {
        try {
            String string = null;
            string.toString(); //Throws NPE
        } catch (NullPointerException exception) {
            StringWriter stringWriter = new StringWriter();
            exception.printStackTrace(new PrintWriter(stringWriter));
            String stackTrace = stringWriter.toString();
            System.out.println(stackTrace);
        }
    }
}
java.lang.NullPointerException: 

Cannot invoke "String.toString()" because "string" is null
 at org.code2care.java.ExceptionAsString.main(ExceptionAsString.java:10)

Process finished with exit code 0

As you can see the exception was printed as a string and the program completed with an exit code of 0

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap