简体   繁体   中英

Write Exceptions to File

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.

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.

You can use:

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

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).

Use

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

to create an appending file writer.

Try this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM