java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to log an exception?

In this example you can see how we can log an exception when it occures. In the code below we are trying to parse an invalid date which will give us a ParseException. To log the exception we call the Logger.log() method, passes the logger Level, add some user friendly message and the Throwable object.

package com.javacoderanch.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");

        try {
            // Try to parsing a wrong date.
            Date date = df.parse("12/30/1990");

            System.out.println("Date = " + date);
        } catch (ParseException e) {
            // Create a Level.SEVERE logging message
            if (logger.isLoggable(Level.SEVERE)) {
                logger.log(Level.SEVERE, "Error parsing date", e);

The code above will produce the following log message.

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