-1

I am supposed to Use Scanner to read int values from a file “input.txt”, Read until end of file is reached, Write all program output to a file “output.txt”, Write all exceptions to a file “error.txt”, and Output each number read.

I understand exceptions for the most part, but I do not understand how to write all exceptions to a text file in Java...

SlackStack
  • 69
  • 2
  • 12
  • Write a `try ... catch` block where you write the exception to `File error.txt` using `Printwriter`. More about `Printwriter` here: http://stackoverflow.com/questions/2885173/how-to-create-a-file-and-write-to-a-file-in-java – Ceelos Mar 23 '16 at 23:48
  • Oh, I did not even think of it that way! Thank you! – SlackStack Mar 23 '16 at 23:50
  • I explained with more detail below. Cheers! – Ceelos Mar 24 '16 at 00:08

3 Answers3

2

Like I wrote in my comment, write a try ... catch block where you write the exception to File error.txt using Printwriter. For instance:

PrintWriter writer = new PrintWriter("error.txt");

try {

//Code to try goes here

} catch (Exception e) {

//You've got an exception. Now print it to error.txt
    writer.write(e.toString());

}

You could test with something simple like:

PrintWriter writer = new PrintWriter("error.txt");
int[] i = new int[1];
try {
    i[10] = 2;
} catch (Exception e) {
    writer.write(e.toString());
}

This results in error.txt being populated with:

java.lang.ArrayIndexOutOfBoundsException: 10

You can print the entire Stack Trace by doing

e.printStackTrace(writer);

Very important that you don't forget to close the PrintWriter or your file won't get printed to. Once you are done writing to the file, close with:

writer.close();
Ceelos
  • 1,076
  • 1
  • 13
  • 33
0

use log4j for logging purpose,

Also , configure it at Error level for printing error into different file.

from your java code, write below line will print whole stack-track to the log file.

commons-logging, it's use likewise:

log.error("Message", exception);
Vishal Gajera
  • 3,798
  • 3
  • 23
  • 49
0

All exceptions have a method: getMessage() that will return the exception as a string. In addition, toString(), which all Java classes should have, gives a little bit more information, since it also calls getMessage().

Cache Staheli
  • 2,897
  • 6
  • 30
  • 41