In this example you can see how we can log an exception when it occurs. 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 org.kodejava.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 {
// Try to parse 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.
Oct 07, 2021 8:21:44 PM org.kodejava.util.logging.LoggingException main
SEVERE: Error parsing date
java.text.ParseException: Unparseable date: "12/30/1990"
at java.base/java.text.DateFormat.parse(DateFormat.java:399)
at org.kodejava.util.logging.LoggingException.main(LoggingException.java:20)
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024