您的位置:首页 > 其它

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

2008-05-09 10:55 483 查看
例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中就是详细的错误信息。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: