java将异常信息通过printStackTrace()写入字符串,,通常情况下我们直接调用e
分享于 点击 16167 次 点评:129
java将异常信息通过printStackTrace()写入字符串,,通常情况下我们直接调用e
通常情况下我们直接调用e.printStackTrace()方法将异常信息写到控制台了。
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) }
我们也可以将异常信息写入到字符串,然后再做处理:
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)}
用户点评