在捕获异常的时候,大家都可能要用到这样的一条语句:e.printStackTrace();
e是Throwable的实例异常对象,用在catch语句中,相当于一个形参,一旦try捕获到了异常,那么就将这个异常信息交给e,由e处理,printStackTrace()是异常类的一个方法。与它重载的方法还有printStackTrace(PrintStream s) 和printStackTrace(PrintWriter s)。
在Throwable类中printStackTrace()内部是这样执行的:
public void printStackTrace() { printStackTrace(System.err);
}
它调用了printStackTrace(PrintStream s)方法。err是System类当中的一个静态PrintStream类型字段。所以它能传递进去。
至于另外两个我不在这里说。
package com.excep; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; // Put printStackTrace() into a String public class TestException { public static void main(String... args) throws FileNotFoundException { try { throw new Exception("for no season"); } catch (Exception e) { PrintWriter pw = new PrintWriter(new File("G:/excep.txt")); e.printStackTrace(pw); pw.flush(); pw.close(); } } // output: // JAVA.LANG.EXCEPTION: FOR NO SEASON // AT COM.EXCEP.TESTEXCEPTION.MAIN(TESTEXCEPTION.JAVA:9)上面这个例子,如果你为了图省事儿,这样写:
e.printStackTrace( new PrintWriter( new File( "G:/excep.txt" )));
那么结果会让你心痛到永远,你在文件中得不到它的异常信息,这是因为PrintWriter提供了一个缓冲区,因为此时可能你写进去的信息没有将缓冲区填满,那么它就不会输出。看来还是得规矩一点,一步一步的来。
通过这个程序可以将错误信息打印到G:/excep.txt中, 然后就可以告诉用户错误信息已经被打印在文件当中了,就相当于一个错误日志。
下面的这个例子将会把错误信息放入到String 中:
package com.excep; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.StringWriter; // Put printStackTrace() into a String public class TestException { public static void main(String... args) throws FileNotFoundException { try { throw new Exception("for no season"); } 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 SEASON // AT COM.EXCEP.TESTEXCEPTION.MAIN(TESTEXCEPTION.JAVA:9) }