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


    }   
}

这是我的代码,我想打印 E:\logfile.txt 中出现的 Evre 异常。请帮助我,我无法做到这一点。

4

2 回答 2

4

使用printStackTrace()带参数的重载PrintStream

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

或者,使用日志框架,例如log4j

于 2013-08-02T08:40:40.567 回答
0

您可以为此编写一个类的静态方法。

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

并记录消息,

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");
}    
于 2013-08-02T08:52:19.573 回答