Tt
Click this widget to change the font size.
CC
Click this widget to change contrast.

Home Page 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | Links | Search | Bio |

Guide to Object-oriented Programming With Java (Buffalo State University Version)


Chapter 11: Java Exceptions and Error Logging

Java provides a number of utilities that allow you to handle exceptions (errors) gracefully. You can even throw your own custom exceptions or the Apache Log4j™ 2 utilities to write errors to a file.

Handling Exceptions Using try/catch

For example, you may want to make sure the user enters a Double and not a letter or other non-number:

double length; // create a variable to hold user input
static Scanner keyboard = new Scanner(System.in); // create an object to request user input
// Accept input for length from the keyboard and check for errors and exceptions
while (true) {
  try { // setup for user input
    System.out.print("Enter the length as a Double: "); // Prompt for user input
    length = keyboard.nextDouble(); // store user input as a Double in the variable length
    System.out.println("You entered " + length); // tell the user you received their valild input
    break; // get out of while loop
  }
  catch ( Exception e) { // test to see if the user did not enter a Double
    // the type Exception is built in so store it in an object variable e
    System.out.println("Sorry, you did not enter a Number.");
    System.out.println("So, this exception happened: " + e);
    keyboard.next(); go back to the while loop and try again
  } // end the try/catch statements
} // end the while loop

Figure 11-1: Handling Exceptions Using try/catch Code

If the user enters a non-number:

Console
Sorry, you did not enter a Number.
So, this exception happened: Invalid Value. Exception:java.util.InputMismatchException

Figure 11-2: Handling Exceptions Using try/catch Output

Java Error Logging

As mentioned above, you can use the Apache Log4j™ 2 utilities to write execptions and errors to a log file.

  1. Download Apache log4j 2 for Eclipse.
  2. If you are doing this on your own machine:
    1. Extract it to: c:\program file\eclipse\plugins
  3. If you are doing this on the classroom machine:
    1. Extract it to: z:\cis425\
  4. Open Eclipse
    1. Right click on your project: edu
    2. Choose: Build Path -> Configure Build Path
    3. Click the Library tab
    4. Click: Add External JARs...
    5. Browse to where you placed the extracted log4j2 files
    6. Add the files you downloaded, log4j-api-2.8.jar and log4j-core-2.8.jar (your version might be newer)
    7. To exit the Build Configuration dialog window, click: OK
    8. Choose: File -> New -> File
    9. Name the file: log4j2.xml
    10. Copy and paste this code (make sure there are no spaces before <?xml in the first line):

      <?xml version="1.0" encoding="UTF-8"?>
      <Configuration status="error">
        <Appenders>
          <Console name="Console" target="SYSTEM_OUT">
             <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
          </Console>
          <File name="log" fileName="log/test.log" append="false">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
          </File>
        </Appenders>
        <Loggers>
          <Root level="trace">
            <AppenderRef ref="log"/>
          </Root>
        </Loggers>
      </Configuration>
      
    11. Choose: Save
Figure 11-3: Setting Up Apache Log4j 2 for Eclipse

Now create a new ApacheLogging class using the ApacheLogging.java which should produce this output in your log -> test.log file:

package edu.buffalostate.cis425.fa10.exercises..put-your-username-here;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

public class ApacheLogging {
  static final Logger log = LogManager.getLogger(ApacheLogging.class.getName());

  public static void recalculatedouble fundAmount,   double fundAmount) {
    log.traceEntry("fundAmount = " + fundAmount);
    fundAmount = fundAmount * (1 + rate);
    log.info("fundAmount = " + fundAmount);
    log.traceExit("new fundAmount = " + fundAmount);
  }

  public static void main(String[] args) {
    int age = 60;
    double retirementFund = 10000;
    int yearsInRetirement = 20;
    String name = "David Johnson";

    for (int i = age; i <= 65; i++) {
      recalculate(retirementFund, 0.2);
    }

    double monthlyPension = retirementFund / yearsInRetirement / 12;
    System.out.println(name + " will have $" + monthlyPension + " per month for retirement.");
    if (monthlyPension < 100) {
      log.fatal("monthlyPension is too low");
    }

    // create a series of log entries to show which
    // levels are printed to which handler's log

    log.trace("finely detailed TRACE message");
    log.debug("detailed DEBUG message");
    log.info("informational message");
    log.warn("warning message");
    log.error("error message");
    log.fatal("fatal message");

    System.exit(0);
  }
}

Figure 11-4: Writing Errors to a Log File ApacheLogging.Java Code
2017-11-22 11:43:08.217 TRACE edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 37 recalculate - Enter fundAmount = 10000.0
2017-11-22 11:43:08.222 INFO  edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 310 recalculate - fundAmount = 12000.0
2017-11-22 11:43:08.223 TRACE edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 40 recalculate - Exit with(new fundAmount = 12000.0)
2017-11-22 11:43:08.224 TRACE edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 37 recalculate - Enter fundAmount = 10000.0
2017-11-22 11:43:08.224 INFO  edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 310 recalculate - fundAmount = 12000.0
2017-11-22 11:43:08.224 TRACE edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 40 recalculate - Exit with(new fundAmount = 12000.0)
2017-11-22 11:43:08.224 TRACE edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 37 recalculate - Enter fundAmount = 10000.0
2017-11-22 11:43:08.225 INFO  edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 310 recalculate - fundAmount = 12000.0
2017-11-22 11:43:08.225 TRACE edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 40 recalculate - Exit with(new fundAmount = 12000.0)
2017-11-22 11:43:08.226 TRACE edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 37 recalculate - Enter fundAmount = 10000.0
2017-11-22 11:43:08.227 INFO  edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 310 recalculate - fundAmount = 12000.0
2017-11-22 11:43:08.227 TRACE edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 40 recalculate - Exit with(new fundAmount = 12000.0)
2017-11-22 11:43:08.227 TRACE edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 37 recalculate - Enter fundAmount = 10000.0
2017-11-22 11:43:08.228 INFO  edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 310 recalculate - fundAmount = 12000.0
2017-11-22 11:43:08.228 TRACE edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 40 recalculate - Exit with(new fundAmount = 12000.0)
2017-11-22 11:43:08.230 TRACE edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 37 recalculate - Enter fundAmount = 10000.0
2017-11-22 11:43:08.230 INFO  edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 310 recalculate - fundAmount = 12000.0
2017-11-22 11:43:08.230 TRACE edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 40 recalculate - Exit with(new fundAmount = 12000.0)
2017-11-22 11:43:08.231 FATAL edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 22 main - monthlyPension is too low
2017-11-22 11:43:08.232 TRACE edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 27 main - finely detailed TRACE message
2017-11-22 11:43:08.232 DEBUG edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 28 main - detailed DEBUG message
2017-11-22 11:43:08.233 INFO  edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 210 main - informational message
2017-11-22 11:43:08.233 WARN  edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 30 main - warning message
2017-11-22 11:43:08.233 ERROR edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 31 main - error message
2017-11-22 11:43:08.234 FATAL edu.buffalostate.cis425.fa10.exercises.assignments.your-username.ApacheLogging 32 main - fatal message

Figure 11-4: Writing Errors to a Log File Output

Let's get started with a TryCatch program!

Help contribute to my OER Resources. Donate with PayPal button via my PayPal account.
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2024 Jim Gerland