现在的位置: 首页 > 综合 > 正文

怎样把e.printStackTrace()这个异常保存到一个字符串变量中如:String str;

2012年03月27日 ⁄ 综合 ⁄ 共 1101字 ⁄ 字号 评论关闭

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中就是详细的错误信息。  

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/dancingtiger/archive/2008/05/09/2421075.aspx

抱歉!评论已关闭.