Java如何记录异常?

在此示例中,您可以看到在异常发生时如何记录异常。在下面的代码中,我们试图解析无效的日期,这将给我们一个ParseException。为了记录异常,我们调用Logger.log()方法,传递记录器Level,添加一些用户友好的消息和Throwable对象。

package org.nhooo.example.util.logging;

import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;

public class LoggingException {
    private static Logger logger = Logger.getLogger(LoggingException.class.getName());

    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        df.setLenient(false);

        try {
            // 尝试解析错误的日期。
            Date date = df.parse("12/30/1990");

            System.out.println("Date = " + date);
        } catch (ParseException e) {
            // 创建一个Level.SEVERE日志消息
            if (logger.isLoggable(Level.SEVERE)) {
                logger.log(Level.SEVERE, "Error parsing date", e);
            }
        }
    }
}

上面的代码将产生以下日志消息。

27 Apr 09 23:32:17 org.nhooo.example.util.logging.LoggingException main
SEVERE: Error parsing date
java.text.ParseException: Unparseable date: "12/30/1990"
    at java.text.DateFormat.parse(DateFormat.java:337)
    at org.nhooo.example.util.logging.LoggingException.main(LoggingException.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:90)