Guide to Object-oriented Programming With Java (University at Buffalo 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:
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.
Download Apache log4j 2 for Eclipse.
If you are doing this on your own machine: Extract it to: c:\program file\eclipse\plugins
If you are doing this on the classroom machine:
Extract it to: z:\cis425\
Open Eclipse
Right click on your project: edu
Choose: Build Path -> Configure Build Path
Click the Library
tab
Click: Add External JARs...
Browse to where you placed the extracted log4j2 files
Add the files you downloaded, log4j-api-2.8.jar
and log4j-core-2.8.jar
(your version might be newer)
To exit the Build Configuration dialog window, click: OK
Choose: File -> New -> File
Name the file: log4j2.xml
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>
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 buffalo.edu.fa23..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 recalculate ( double 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 buffalo.edu.fa23.assignments.your-username .ApacheLogging 37 recalculate - Enter fundAmount = 10000.0
2017-11-22 11:43:08.222 INFO buffalo.edu.fa23.assignments.your-username .ApacheLogging 310 recalculate - fundAmount = 12000.0
2017-11-22 11:43:08.223 TRACE buffalo.edu.fa23.assignments.your-username .ApacheLogging 40 recalculate - Exit with(new fundAmount = 12000.0)
2017-11-22 11:43:08.224 TRACE buffalo.edu.fa23.assignments.your-username .ApacheLogging 37 recalculate - Enter fundAmount = 10000.0
2017-11-22 11:43:08.224 INFO buffalo.edu.fa23.assignments.your-username .ApacheLogging 310 recalculate - fundAmount = 12000.0
2017-11-22 11:43:08.224 TRACE buffalo.edu.fa23.assignments.your-username .ApacheLogging 40 recalculate - Exit with(new fundAmount = 12000.0)
2017-11-22 11:43:08.224 TRACE buffalo.edu.fa23.assignments.your-username .ApacheLogging 37 recalculate - Enter fundAmount = 10000.0
2017-11-22 11:43:08.225 INFO buffalo.edu.fa23.assignments.your-username .ApacheLogging 310 recalculate - fundAmount = 12000.0
2017-11-22 11:43:08.225 TRACE buffalo.edu.fa23.assignments.your-username .ApacheLogging 40 recalculate - Exit with(new fundAmount = 12000.0)
2017-11-22 11:43:08.226 TRACE buffalo.edu.fa23.assignments.your-username .ApacheLogging 37 recalculate - Enter fundAmount = 10000.0
2017-11-22 11:43:08.227 INFO buffalo.edu.fa23.assignments.your-username .ApacheLogging 310 recalculate - fundAmount = 12000.0
2017-11-22 11:43:08.227 TRACE buffalo.edu.fa23.assignments.your-username .ApacheLogging 40 recalculate - Exit with(new fundAmount = 12000.0)
2017-11-22 11:43:08.227 TRACE buffalo.edu.fa23.assignments.your-username .ApacheLogging 37 recalculate - Enter fundAmount = 10000.0
2017-11-22 11:43:08.228 INFO buffalo.edu.fa23.assignments.your-username .ApacheLogging 310 recalculate - fundAmount = 12000.0
2017-11-22 11:43:08.228 TRACE buffalo.edu.fa23.assignments.your-username .ApacheLogging 40 recalculate - Exit with(new fundAmount = 12000.0)
2017-11-22 11:43:08.230 TRACE buffalo.edu.fa23.assignments.your-username .ApacheLogging 37 recalculate - Enter fundAmount = 10000.0
2017-11-22 11:43:08.230 INFO buffalo.edu.fa23.assignments.your-username .ApacheLogging 310 recalculate - fundAmount = 12000.0
2017-11-22 11:43:08.230 TRACE buffalo.edu.fa23.assignments.your-username .ApacheLogging 40 recalculate - Exit with(new fundAmount = 12000.0)
2017-11-22 11:43:08.231 FATAL buffalo.edu.fa23.assignments.your-username .ApacheLogging 22 main - monthlyPension is too low
2017-11-22 11:43:08.232 TRACE buffalo.edu.fa23.assignments.your-username .ApacheLogging 27 main - finely detailed TRACE message
2017-11-22 11:43:08.232 DEBUG buffalo.edu.fa23.assignments.your-username .ApacheLogging 28 main - detailed DEBUG message
2017-11-22 11:43:08.233 INFO buffalo.edu.fa23.assignments.your-username .ApacheLogging 210 main - informational message
2017-11-22 11:43:08.233 WARN buffalo.edu.fa23.assignments.your-username .ApacheLogging 30 main - warning message
2017-11-22 11:43:08.233 ERROR buffalo.edu.fa23.assignments.your-username .ApacheLogging 31 main - error message
2017-11-22 11:43:08.234 FATAL buffalo.edu.fa23.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!