How can I get the current stack trace in Java?

前端 未结 21 3105
耶瑟儿~
耶瑟儿~ 2020-11-21 23:49

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 -

相关标签:
21条回答
  • 2020-11-22 00:11

    Another solution (only 35 31 characters):

    new Exception().printStackTrace();   
    new Error().printStackTrace();
    
    0 讨论(0)
  • 2020-11-22 00:11

    Silly me, it's Thread.currentThread().getStackTrace();

    0 讨论(0)
  • 2020-11-22 00:14

    Tony, as a comment to the accepted answer, has given what seems to be the best answer which actually answers the OP's question:

    Arrays.toString(Thread.currentThread().getStackTrace()).replace( ',', '\n' );
    

    ... the OP did NOT ask how to get a String from the stack trace from an Exception. And although I'm a huge fan of Apache Commons, when there is something as simple as the above there is no logical reason to use an outside library.

    0 讨论(0)
  • 2020-11-22 00:15

    On android a far easier way is to use this:

    import android.util.Log;
    String stackTrace = Log.getStackTraceString(exception); 
    
    0 讨论(0)
  • 2020-11-22 00:17
    for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
        System.out.println(ste);
    }
    
    0 讨论(0)
  • 2020-11-22 00:18

    Maybe you could try this:

    catch(Exception e)
    {
        StringWriter writer = new StringWriter();
        PrintWriter pw = new PrintWriter(writer);
        e.printStackTrace(pw);
        String errorDetail = writer.toString();
    }
    

    The string 'errorDetail' contains the stacktrace.

    0 讨论(0)
提交回复
热议问题