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.



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();

Cannot invoke "String.toString()" because "string" is null

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

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:

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