Put printStackTrace() into a StringTag(s): Language

public class TestException {
    public static void main(String args[]) {
      try {
          throw new Exception("for no reason!");
      }
      catch (Exception e) {
          e.printStackTrace();
      }
    }2
    // output :
    //   java.lang.Exception: for no reason!
    //      at TestException.main(TestException.java:8)   
}

You redirect the StackTrace to a String with a StringWriter/PrintWriter :

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

public class TestException {
    public static void main(String args[]) {
      try {
          throw new Exception("for no reason!");
      }
      catch (Exception e) {
          StringWriter sw = new StringWriter();
          PrintWriter pw = new PrintWriter(sw);
          e.printStackTrace(pw);
          System.out.println(sw.toString().toUpperCase());
      }
    }
    // output :
    //    JAVA.LANG.EXCEPTION: FOR NO REASON!
    //        AT TESTEXCEPTION.MAIN(TESTEXCEPTION.JAVA:7)
}

This can be useful if you want to format the StackTrace before showing it to the user.




If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2012
[ home ]