Write Exceptions to File

拈花ヽ惹草 提交于 2019-12-21 03:36:28

问题


The java project i have created is to be tested for 1800 cases and the output of each case has to matched with the golden(desired) output. I have created a perl script for this and running it on cygwin.

There are a few cases which throw exceptions but they are wrongly considered to be correct. I want to add a try catch block in java code so that if any exception is thrown it is caught and stack trace is printed on the file 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();
    }
}

But this overwrites the previous file contents and finally file contains the last thrown exception. How can i write catch block so that stackTrace is printed and contents of file are intact and not overwritten each time.


回答1:


Use this constructor instead:

new FileWriter ("exception.txt", true);

It is described here.

EDIT: As per Jon's comment below:

If you want to print the entire stack trace, use printStackTrace:

fw = new FileWriter ("exception.txt", true);
pw = new PrintWriter (fw);
e.printStackTrace (pw);

Also, use the appropriate close calls after that.




回答2:


You can use:

FileOutputStream fos = new FileOutputStream(new File("exception.txt"), true);  
PrintStream ps = new PrintStream(fos);  
e.printstacktrace(ps);



回答3:


Here is a program that demonstrates what I think you need:


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);
      }
   }
}

It uses the printStackTrace(PrintWriter) method on Throwable to print the entire stack trace to the end of a file called "exception.txt", then there's a main() method which demonstrates usage with two sample exceptions. If you run it in your IDE, you should find that you get a file with two stack traces written to it (works for me).




回答4:


Use

FileWriter fstream=new FileWriter("exception.txt", true);

to create an appending file writer.




回答5:


Try this:

PrintStream printStream = new PrintStream(new File("exception.txt"));
try {   
     //error proven code
} catch (Exception exception) {
     exception.printStackTrace(printStream);
}



回答6:


Try this:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;

public class ErrorLogger
{
    private Logger logger;

    public ErrorLogger()
    {
        logger = Logger.getAnonymousLogger();

        configure();
    }

    private void configure()
    {
        try
        {
            String logsFolder = "logs";
            Files.createDirectories(Paths.get(logsFolder));
            FileHandler fileHandler = new FileHandler(logsFolder + File.separator + getCurrentTimeString() + ".log");
            logger.addHandler(fileHandler);
            SimpleFormatter formatter = new SimpleFormatter();
            fileHandler.setFormatter(formatter);
        } catch (IOException exception)
        {
            exception.printStackTrace();
        }

        addCloseHandlersShutdownHook();
    }

    private void addCloseHandlersShutdownHook()
    {
        Runtime.getRuntime().addShutdownHook(new Thread(() ->
        {
            // Close all handlers to get rid of empty .LCK files
            for (Handler handler : logger.getHandlers())
            {
                handler.close();
            }
        }));
    }

    private String getCurrentTimeString()
    {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        return dateFormat.format(new Date());
    }

    public void log(Exception exception)
    {
        logger.log(Level.SEVERE, "", exception);
    }
}

Usage:

ErrorLogger errorLogger = new ErrorLogger();

try
{
    throw new Exception("I died!");
} catch (Exception exception)
{
    errorLogger.log(exception);
}


来源:https://stackoverflow.com/questions/9923673/write-exceptions-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!