天天看點

怎樣把e.printStackTrace()這個異常儲存到一個字元串變量中如:String str;

例1:

import   java.io.*;  

  public   class   Ping   {  

          public   static   void   main(String[]   args)   {  

                  String   command="pig   www.sohu.com";  

                  StringWriter   sw   =   new   StringWriter();  

          try   {  

              Process   child=Runtime.getRuntime().exec(command);  

              child.waitFor();  

              System.out.println(child.exitValue());  

          }   catch   (   InterruptedException   ie   )   {    

                  System.out.println(   ie   );  

                  ie.printStackTrace(new   PrintWriter(sw));  

          }   catch   (IOException   ioe)   {  

                  System.out.println(   ioe   );  

                  ioe.printStackTrace(new   PrintWriter(sw));  

          }  

          System.out.println(sw);  

          }  

  }  

  sw.toString()就是你要的String

e.printStackTrace是定向到err的輸出中,如果要e的資訊直接e.toString就可以了

如果用e.toString,資訊不全面,不能知道錯誤的具體行數。  

  StringWriter   sw=new   StringWriter();  

  ………  

  ………  

  e.printStackTrace(new   PrintWriter(sw,true));  

  String   str=sw.toString;  

  //str中就是詳細的錯誤資訊。