例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中就是详细的错误信息。
本文通过一个Java程序示例,展示了如何使用StringWriter和PrintWriter来捕获并处理异常信息,以便于进行更细致的日志记录和错误排查。
961

被折叠的 条评论
为什么被折叠?



