1

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) 
2
  • What type of program are you running? A console application, a web application, Android, something else? Commented Aug 29, 2016 at 6:19
  • please show the code of your Main class and the input that is causing the exception. Commented Aug 29, 2016 at 13:08

2 Answers 2

2
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; } 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.