如何打印异常堆栈跟踪

时间:2016-06-12 10:29:37

标签: java exception-handling

package javaapplication1;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class multicatch {
    public static void main(String[] args) throws FileNotFoundException {

            Throwable t = new Exception("Tis is some kind of throwable exception");  
            PrintWriter ps=new PrintWriter("D:\\fff.txt");
  t.printStackTrace(ps);
    }
}

该程序创建" fff.txt"并且它不会在该文件中打印任何内容。

4 个答案:

答案 0 :(得分:1)

尝试在结束时关闭PrintWriter。

ps.close();

答案 1 :(得分:0)

这有效:

 import java.io.FileNotFoundException;
 import java.io.FileWriter;
 import java.io.IOException;
 import java.io.PrintWriter;
  public class multicatch {
public static void main(String[] args) throws FileNotFoundException, IOException {

        Throwable t = new Exception("This is some kind of throwable exception");  
        PrintWriter ps=new PrintWriter(new FileWriter("F:\\fff.txt", true));
    ps.write(t.getMessage());

        ps.close();
  }      
 }

答案 2 :(得分:0)

package javaapplication1;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class throwexception {
    public static void main(String[] args) throws FileNotFoundException {

            Throwable t = new Exception("Throwable exception");  
            PrintWriter ps=new PrintWriter("D:\\fff.txt");
            t.printStackTrace();
  t.printStackTrace(ps);
  ps.close();
    }
}

需要关闭流...

答案 3 :(得分:-1)

使用尝试

捕捉您感兴趣的例外

try{ //...
}
catch (Exception ex) {
    ex.printStackTrace(new PrintStream(yourOutputStream));
    //or
    e.printStackTrace(System.out);
}

请注意,可以将堆栈跟踪重定向到所需的输出流。