2
public class myclass
{
    // Main method
    public static void main (String args[])
    {
        // Stream to write file
 try {
    int a=100;
     int b=a/0;
    System.out.println(b);
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}       


    }   
}

This my code i want to Print what Evre Exception is coming in E:\logfile.txt. please help me i am Unable to do this .

Anil Kumar
  • 135
  • 1
  • 2
  • 13

2 Answers2

4

Use the printStackTrace() overload which takes a PrintStream parameter:

http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)

Alternatively, use a logging framework, such as log4j.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
0

You can write a static method of a class for this.

public class Logbook {

    // path to logbook
    private String path = "E:\logfile.txt";

    // static method
    public static boolean Log(String message) {
        try {
            File f = new File(path);
            // append the text file
            FileWriter fileWriter = new FileWriter(file,true);

            // append text to file by using a buffer
            BufferedWriter bw  = new BufferedWriter(fileWriter);
            fileWriter.append(message);

            // close buffer
            bufferFileWriter.close();

            // tell that it has succeed
            return true;
        }
        catch (Exception e) {
            return false;
        }
    }

and to log the message,

catch (Exception e) {
    // log file
    if (Logbook.Log(e.getMessage())) System.out.println("Error caught and got logged");
    else System.out.println("Error caught but logging has failed");
}    
KarelG
  • 5,176
  • 4
  • 33
  • 49