Monday, 21 December 2015

Get shortened stacktrace after exception in Java


Sometimes, we require only set of lines from the stacktrace, so a generic method to get the required number of line from stacktrace.

import java.io.PrintWriter;
import java.io.StringWriter;

public static void main(String[] args) {
       try {
       throw new Exception("Malformed Exception");
   } 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();
}

No comments:

Post a Comment