Stack Trace is a list of method calls from the point when the application was started to the point where the exception was thrown.
Stack Trace is useful to debug the code and see from where exactly the Exception was originated and root cause of the problem. Stack trace of the exception can be printed to the standard error by calling the public void printStackTrace() method. Consider below given example.
Stack Trace is useful to debug the code and see from where exactly the Exception was originated and root cause of the problem. Stack trace of the exception can be printed to the standard error by calling the public void printStackTrace() method. Consider below given example.
Many times for debugging purposes, we'd like to convert the stack trace to a String so we can log it to our log file.
The following code shows how to do that -
package com.anjan.st;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ConvertSTToString {
public static void main(String args[]) {
try {
int i = 10 / 0;
}catch(Exception e) {
System.out.println("Stack Trace ***\n");
e.printStackTrace();
}
try {
int i = 10 / 0;
}catch(Exception e) {
System.out.println("\nStack Trace as String **** \n"+convertToString(e));
}
}
/*
* This method will convert Stack Trace to String
*/
private static String convertToString(Throwable t) {
String strException = "";
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
t.printStackTrace(printWriter);
strException = stringWriter.toString();
return strException;
}
}
Output -
Stack Trace ***
java.lang.ArithmeticException: / by zero
at com.anjan.st.ConvertSTToString.main(ConvertSTToString.java:11)
Stack Trace as String ****
java.lang.ArithmeticException: / by zero
at com.anjan.st.ConvertSTToString.main(ConvertSTToString.java:18)
No comments:
Post a Comment