logging
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.
