Home » Core Java » util » logging » Log an exception

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Log an exception

With this example we are going to demonstrate how to log an exception. In order to do so, we will use a DateFormat and parse a String pattern to create a new Date. In short, to log the ParseException that occurs you should:

  • Create a new SimpleDateFormat with a specific String pattern.
  • Invoke the setLenient(boolean lenient) API method of the DateFormat, setting the lenient to false. Thus, the inputs of the DateFormat parser must match this object’s format, or else a ParseException will be thrown.
  • Invoke the log(Level level, String msg, Throwable thrown) API method to log a message, with the associated Throwable information.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

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 LogException {
	
    private static Logger logger = Logger.getLogger(LogException.class.getName());
 
    public static void main(String[] args) {

  DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

  df.setLenient(false);
 

  try {


// Set wrong date


Date date = df.parse("11/08/1984");
 


System.out.println("Date = " + date);

  } catch (ParseException e) {




  	// Create log message 


if (logger.isLoggable(Level.SEVERE)) {


    logger.log(Level.SEVERE, "Error parsing date", e);


}

  }
    }
}

Output:

Αυγ 12, 2012 1:30:09 ΜΜ com.javacodegeeks.snippets.core.LogException main
SEVERE: Error parsing date
java.text.ParseException: Unparseable date: "11/08/1984"
	at java.text.DateFormat.parse(Unknown Source)
at com.javacodegeeks.snippets.core.LogException.main(LogException.java:22)

 
This was an example of how to log an exception in Java.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of