It seems like there should be some simple way to write a stack trace to the
console any time you like, even if an exception has not occurred but I'm
blanking out when I try to think of how that could be done. I feel sure it
is possible and is easy so maybe my brain is just not firing on all
cylinders today....
Can anyone help?
--
Rhino
There's a fairly easy workaround:
package exceptions;
public class PrintStackTrace {
public static void main( String[] args ) {
test();
}
private static void test() {
Throwable t = new Throwable();
t.fillInStackTrace();
StackTraceElement[] stackTrace = t.getStackTrace();
for ( int i = 0; i < stackTrace.length; ++i ) {
StackTraceElement element = stackTrace[i];
System.out.println( element );
}
}
}
Kind regards
robert
Robert Klemme wrote:
> Throwable t = new Throwable();
> t.fillInStackTrace();
> StackTraceElement[] stackTrace = t.getStackTrace();
> for ( int i = 0; i < stackTrace.length; ++i ) {
> StackTraceElement element = stackTrace[i];
> System.out.println( element );
> }
Indeed, this can be done a little easier:
new Exception().printStackTrace();
Ciao,
Ingo
>Is there any way to print a stack trace if no exception has taken place?
see http://mindprod.com/jgloss/trace.html
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
And even more easily,
Thread.dumpStack();
Dan.
--
Daniel Dyer
http://www.dandyer.co.uk
Amusingly enough, Sun's source code shows that the Thread.dumpStack
method does the same thing, except that it gives the Exception's
constructor a String parameter saying "Stack Trace".
= Steve =
--
Steve W. Jackson
Montgomery, Alabama
I imagine this happened after lots of developpers asked for a way to get
the stack trace and balked when Sun told them to just create a new Exception
("isn't that wasteful?!" they'd complain). So to placate them, Sun created
this new method and everyone lived happily ever after.
- Oliver
That /is/ amusing.
But Oliver did write:
> I imagine this happened after lots of developpers asked for a way to
> get the stack trace and balked when Sun told them to just create a new
> Exception ("isn't that wasteful?!" they'd complain). So to placate them,
> Sun created this new method and everyone lived happily ever after.
Has the advantage too that the functionality is now available in the "right"
place. And Sun can, at a later date, move the actual implementation too.
-- chris