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
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!