Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 229
Rog Matthews Avatar asked Mar 29 '12 10:03

Rog Matthews


People also ask

How do I create an exception to a file?

Go to Start > Settings > Update & Security > Windows Security > Virus & threat protection. Under Virus & threat protection settings, select Manage settings, and then under Exclusions, select Add or remove exclusions. Select Add an exclusion, and then select from files, folders, file types, or process.

What is an exception file?

Working with files will make your programs fast when analyzing masses of data. Exceptions are special objects that any programming language uses to manage errors that occur when a program is running.

How do you write an exception to a text file in Java?

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

What is file exception in Python?

An exception is a Python object that represents an error. When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.


1 Answers

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.

like image 65
3 revs Avatar answered Oct 10 '22 16:10

3 revs