将异常写入文件

Rog*_*ews 13 java exception-handling

我创建的java项目将测试1800个案例,每个案例的输出必须与黄金(所需)输出相匹配.我为此创建了一个perl脚本并在cygwin上运行它.

有一些情况会抛出异常,但它们被错误地认为是正确的.我想在java代码中添加一个try catch块,这样如果抛出任何异常,就会捕获它并在文件上打印堆栈跟踪exception.txt.

Pseudo Java code:
main()
{
    try
    {
       ... //complete code of main()
    }
    catch (Exception e)
    {
         FileWriter fstream=new FileWriter("exception.txt");
         BufferedWriter out=new BufferedWriter(fstream);
         out.write(e.toString());
         out.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是这会覆盖以前的文件内容,最后文件包含最后抛出的异常.如何编写catch块以便打印stackTrace并且文件内容完好无损且每次都不会被覆盖.

Arj*_*kar 22

请改用此构造函数:

new FileWriter ("exception.txt", true);
Run Code Online (Sandbox Code Playgroud)

这里描述.

编辑:根据Jon的评论如下:

如果要打印整个堆栈跟踪,请使用printStackTrace:

fw = new FileWriter ("exception.txt", true);
pw = new PrintWriter (fw);
e.printStackTrace (pw);
Run Code Online (Sandbox Code Playgroud)

此外,close在此之后使用适当的调用.


Kay*_*ser 10

您可以使用:

FileOutputStream fos = new FileOutputStream(new File("exception.txt"), true);  
PrintStream ps = new PrintStream(fos);  
e.printstacktrace(ps);
Run Code Online (Sandbox Code Playgroud)


Jon*_*Jon 7

这是一个程序,演示了我认为你需要的东西:


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;

public class StrackTraceAppender {

   public static void main(String[] args) {
      try {
         thrower("Oh noes!");
      } catch (Exception e) {
         appendToFile(e);
      }

      try {
         thrower("I died!");
      } catch (Exception e) {
         appendToFile(e);
      }
   }

   public static void thrower(String message) throws Exception {
      throw new RuntimeException(message);
   }

   public static void appendToFile(Exception e) {
      try {
         FileWriter fstream = new FileWriter("exception.txt", true);
         BufferedWriter out = new BufferedWriter(fstream);
         PrintWriter pWriter = new PrintWriter(out, true);
         e.printStackTrace(pWriter);
      }
      catch (Exception ie) {
         throw new RuntimeException("Could not write Exception to file", ie);
      }
   }
}

它使用printStackTrace(PrintWriter)Throwable上的方法将整个堆栈跟踪打印到名为"exception.txt"的文件的末尾,然后有一个main()方法用于演示两个示例异常的用法.如果你在IDE中运行它,你会发现你得到一个写有两个堆栈跟踪的文件(适合我).


And*_*s_D 5

使用

FileWriter fstream=new FileWriter("exception.txt", true);
Run Code Online (Sandbox Code Playgroud)

创建一个附加文件编写器.