Fetch only first N lines of a Stack Trace

If you just want to truncate the stack trace, you can print the entire stack trace to a StringWriter then remove what you don't want:

public static void main(String[] args) throws ParseException {
    try {
        throw new Exception("Argh!");
    } catch (Exception e) {
        System.err.println(shortenedStackTrace(e, 1));
    }
}

public static String shortenedStackTrace(Exception e, int maxLines) {
    StringWriter writer = new StringWriter();
    e.printStackTrace(new PrintWriter(writer));
    String[] lines = writer.toString().split("\n");
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < Math.min(lines.length, maxLines); i++) {
        sb.append(lines[i]).append("\n");
    }
    return sb.toString();
}

Alternatively, use e.getStackTrace() to obtain a StackTraceElement[] array. This gives you the caller stack (from inner to outer), but not the error message. You'll have to use e.getMessage() to get the error message.

Some logging frameworks can be configured to truncate stack traces automatically. E.g. see this question and answer about log4j configuration.

If you just want to see the stack trace at any point in the code, you can get the elements from the Thread.currentThread() object:

Thread.currentThread().getStackTrace();

You can use the ex.getStackTrace() to get the stack elements, the StackTraceElement contains one line of the full stacks, then print print what ever you want.

StackTraceElement[] elements = ex.getStackTrace();
print(elements[0]);

This method displays i lines of the stack trace, skipping the first two.

public static String traceCaller(Exception ex, int i) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    StringBuilder sb = new StringBuilder();
    ex.printStackTrace(pw);
    String ss = sw.toString();
    String[] splitted = ss.split("\n");
    sb.append("\n");
    if(splitted.length > 2 + i) {
        for(int x = 2; x < i+2; x++) {
            sb.append(splitted[x].trim());
            sb.append("\n");
        }
        return sb.toString();
    }
    return "Trace too Short.";
}

The first two lines are the exception name and the method that called traceCaller(). Tweak it if you want to show these lines.

Thanks go to @BrianAgnew (stackoverflow.com/a/1149712/1532705) for the StringWriter PrintWriter idea


I'm assuming from what you are asking, that you don't have an exception to deal with. In which case you can get the current stack trace from:

StackTraceElement[] elements = Thread.currentThread().getStackTrace()

This will tell you pretty much everything you need to know about where you've come from in the code.