4. Types of Exception
• Within JVM there are 2 types of exceptions
▫ Checked
Enforced by methods
▫ Unchecked
May lead to thread unraveling and poor visibility
5. Catching Exceptions
• Try
▫ Tells that the enclosed code segment could raise a
potential exception
• Catch
▫ What exceptions to handle
▫ If no catch for a checked exception, the compiler
will generate an error.
6. Guaranteed Execution of Cleanup Code
• To write code that executes when control leaves
a code segment
▫ Finally
7. Throwing Exceptions
• Making account for an exceptional problem by
throwing an exception
• The execution will not continue on current code
path
8. Catching Multiple Exceptions
• Using different catch clauses
▫ Most-Specific to Most-General
• A new Java construct
▫ “|” operator
▫ Java 7 Feature
• Pokemon® Exception
▫ catch (Exception e)
▫ Catches every exception type and treat them same
▫ May catch unwanted exceptions (i.e.
OutOfMemoryException)
9. Catching the Uncaught Exceptions
• How to know when a thread is being terminated
because of an uncaught exception?
▫ Register an ExceptionHandler
Per thread
Thread.currentThread().setUncaughtExceptionHandler
Globally
Thread.setDefaultUncaughtExceptionHandler
10. Managing Resource with try/catch
• Why?
▫ Managing resources problematic
▫ Should properly dispose once used
▫ Limited and cause performance degradation
• ARM
▫ Automatic Resource Management
▫ Java 7
▫ Try-with-resource block
▫ java.lang.AutoClosable
11. Creating an Exception Class
• extend RuntimeException
▫ Unchecked exceptions
▫ But,
Leads to poor exception handling
• extend Exceptions
• Rule of Thumb:
▫ If it’s possible to recover from an exception, extend the
Exception class.
▫ Else, if it is not reasonable to expect to be recovered
from the exception (i.e. NullPointerException), extend
RuntimeException.
12. Re-throwing the Caught Exception
• With Java 7, JVM will bubble the exception to
the appropriate type
• Checked exceptions have to be defined in the
method declaration
13. Logging Events
• SLF4J
▫ A Simple Logging Facade for Java
▫ An abstraction for various logging frameworks
Java Logging API
Log4j
Jakarta Commons Logging
14. log4j
• Enabling logging at runtime
• Fully Configurable at runtime via external
configuration file
• Gentle learning curve
• 3 Main Parts
▫ Loggers
▫ Appenders
▫ Layouts
15. log4j
• Logger
▫ Named entities
▫ Has a naming hierarchy
▫ Provides run-time control on which statements
are printed or not
▫ Root logger
It always exists
It cannot be retrieved by name
Logger.getRootLogger ();
16. log4j
• Log Levels - http://goo.gl/jOWg8
▫ TRACE
▫ DEBUG
Messages in this level contain extensive contextual
information. They are mostly used for problem diagnosis.
▫ INFO
contain some contextual information
▫ WARN
a potential problem in the system – i.e. a security valnarability
▫ ERROR
▫ FATAL
• Level inheritance
• A logging request is said to be enabled,
▫ If the level of the logging request >= logger’s log level
17. log4j
• Basic Selection Rule
▫ A log request of level p in a logger with (either
assigned or inherited, whichever is appropriate)
level q, is enabled if p >= q.
• TRACE < DEBUG < INFO < WARN < ERROR <
FATAL
18. log4j
• .getLogger(…)
▫ Will always return a reference to the exact same
object
• Log4j makes it easy to name loggers by software
component
▫ statically instantiating a logger in each class
▫ Logger name as the class name
▫ A way to define loggers
The origin of the log message is easily identified
19. log4j
• Loggers
• Appenders
▫ log4j allows logging requests to print to multiple
destinations
▫ An output destination is called appender. Currently
appenders exists for;
Console
Files
GUI Components
Remote Sockets, Servers, JMS, NT Event Loggers, Syslog
Daemons
Logging Asynchronously
20. log4j
• Appenders
▫ Each enabled logging request for a given logger
will be forwarded to all the appenders in that
logger as well as the appenders higher in the
hierarchy
• Appender Additivly
▫ The output of a log statement of logger C will go to
all the appenders in C and its ancestors.
▫ Additivity flag
22. Cons
log4j ole
root
S X
File
Aditivity = false
X.Y
X.Y.
Z
23. log4j
• Loggers
• Appenders
• Layout
▫ Customizes log output format
▫ Conversion pattern like C languages printf
▫ http://logging.apache.org/log4j/1.2/apidocs/org/
apache/log4j/PatternLayout.html
▫ Ex:
conversion pattern “%r [%t] %-5p %c - %m%n [%x]”
176 [main] INFO org.foo.Bar - Hello World [1581616
4464 116416 1161]
24. log4j
• Nested Diagnostic Contexts (NDC)
• Performance and Best Practices
▫ Log message parameter construction
▫ logger.isDebugEnabled
▫ Choose appropriate logging level
▫ Log message format
▫ Logging in a production environment
Logging sensitive data
Log file management
Correlating specific execution order