What is PrintStackTrace in Java

Output of a StackTrace in Java

15.08.2012

Here is a very brief description of how easy it is to write a StackTrace of an exception in Java into one or to output it on the console.

I've seen a number of interesting ways people try to take a StackTrace apart and then put it back together with an or. And all of this so that it can then be output on the console or displayed in a dialog.

However, this is usually completely superfluous. The following snippet of code shows an easy way to get it right. First one is provoked and caught in the block. Because the class that offers the method, a can be used to have the StackTrace write into it. It can then be easily output.

try {string t = null; t.trim (); } catch (exception e) {final ByteArrayOutputStream stream = new ByteArrayOutputStream (); e.printStackTrace (new PrintStream (stream)); System.out.println (stream); }

It should be noted that the method is called automatically by, i.e. if you want to save the StackTrace in a variable, then it has to be called.

String stackTrace = "No StackTrace"; try {string t = null; t.trim (); } catch (exception e) {final ByteArrayOutputStream stream = new ByteArrayOutputStream (); e.printStackTrace (new PrintStream (stream)); stackTrace = stream.toString (); }

It should be noted that the class offers the function which has an array of elements as return value. This method should only be used if you intend to change individual lines of the StackTrace in any way. For example, to generate an HTML display in which the second line is highlighted: (The functions f1, f2, f3 were only inserted so that the StackTrace has several lines.)

public static void main (String [] args) {try {f1 (); } catch (Exception e) {StringBuilder sb = new StringBuilder (); sb = sb.append (" Exception type: "); sb = sb.append (e.toString ()); sb = sb.append ("

"); StackTraceElement [] ste = e.getStackTrace (); for (int i = 0; i "); } sb = sb.append (""); sb = sb.append (ste [i]); sb = sb.append ("