Java Reference
In-Depth Information
understand what events are occurring without the need for debugging the code. This is
especially true in production environments where there isn't the opportunity for live
debugging. In that sense, logging collects clues on what is occurring (most likely what
went wrong) and helps you troubleshoot production problems. Many developers
choose to utilize a structured logging framework to provide more robust logging for an
application. A solid logging framework with a sound methodology will save many late
nights at work wondering, “what happened?”
Logging for Java is very mature. There are many open source projects that are
widely accepted as the de facto standard for logging. In the recipes in this chapter, you
will use Java's Logging framework and the Simple Logging Façade for Java (SLF4).
Both of these projects together create a good-enough solution for most logging needs.
For the recipes involving SLF4J and Log4j, download SLF4J ( ht-
tp://www.slf4j.org/ ) and put it in your project's dependency path.
9-1. Catching Exceptions
Problem
You want to gracefully handle any exceptions generated from your code.
Solution
Use the built-in try / catch language construct to catch exceptions. Do so by wrap-
ping any blocks of code that may throw an exception within a try/catch block. In
the following example, a method is used to generate a Boolean value to indicate wheth-
er a specified string is greater than five characters long. If the string that's passed as an
argument is null , a NullPointerException is thrown by the length() meth-
od and caught within the catch block.
private void start() {
System.out.println("Is th string 1234 longer than
5 chars?:"+
isStringShorterThanFiveCharacters("1234"));
System.out.println("Is th string 12345 longer than
5 chars?:"+
isStringShorterThanFiveCharacters("12345"));
Search WWH ::




Custom Search