How do I get the exception stack trace in Java? I can use Thread.currentThread().getStackTrace().but get error linenumber
Correctly:
java.lang.ArithmeticException: / by zero
at me.edagarli.Main.main(Main.java:32)
Wrongly:
java.lang.ArithmeticException: / by zero
java.lang.Thread.getStackTrace(Thread.java:1589)
me.edagarli.Main.main(Main.java:54)
public String getFullErrorDescription(Exception exceptionObj ) {
String textmsg = "";
if (exceptionObj != null) {
StackTraceElement[] ste = exceptionObj.getStackTrace();
textmsg += "\nIn File : " + ste[index].getClassName() + " ";
textmsg += "\nIn Method : " + ste[index].getMethodName() + "() ";
textmsg += "\nAt Line :" + ste[index].getLineNumber() + " ";
}
System.err.println(textmsg);
return textmsg;
}
If you need to have stacktrace messages into String instance you can use:
public String getStackTraceAsString(Exception ex){
StackTraceElement[] elements = ex.getStackTrace();
String stacktraceMessage = "";
for(StackTraceElement element : elements){
stacktraceMessage += "\nIn File : " + element.getClassName() + " ";
stacktraceMessage += "\nIn Method : " + element.getMethodName() + " ";
stacktraceMessage += "\nAt Line :" + element.getLineNumber() + " ";
}
return stacktraceMessage;
}
If you need only print stacktrace you can use printStackTrace method:
try{
int a = 100 / 0;
}catch (Exception ex){
ex.printStackTrace();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.