Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the current stack trace in Java?

How do I get the current stack trace in Java, like how in .NET you can do Environment.StackTrace?

I found Thread.dumpStack() but it is not what I want - I want to get the stack trace back, not print it out.

like image 829
ripper234 Avatar asked Jul 01 '09 13:07

ripper234


People also ask

How can I get current stack trace?

You can use Thread. currentThread(). getStackTrace() . That returns an array of StackTraceElement s that represent the current stack trace of a program.

How do I print a full stack trace?

Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.

What is the stack trace in Java?

A stack trace (also known as a stack backtrace) is a report of the active stack frames at a certain point in time during a thread's execution. Java's Throwable class (in the java. lang package) provides methods to print a stack trace, fill in a stack trace, and access a stack trace's elements.

How do I read a stack trace file?

To read this stack trace, start at the top with the Exception's type - ArithmeticException and message The denominator must not be zero . This gives an idea of what went wrong, but to discover what code caused the Exception, skip down the stack trace looking for something in the package com.


2 Answers

You can use Thread.currentThread().getStackTrace().

That returns an array of StackTraceElements that represent the current stack trace of a program.

like image 75
jjnguy Avatar answered Sep 27 '22 20:09

jjnguy


Thread.currentThread().getStackTrace(); 

is fine if you don't care what the first element of the stack is.

new Throwable().getStackTrace(); 

will have a defined position for your current method, if that matters.

like image 43
Yishai Avatar answered Sep 27 '22 19:09

Yishai