Upload
azeemigi
View
389
Download
0
Tags:
Embed Size (px)
Citation preview
Exception & LoggingAzeem MumtazSoftware Engineer
Introduction
•Why Exceptions?▫To describe exceptional circumstances▫To interrupt the current flow
•In Java▫Exception are thrown and caught
Exception Class Hierarchy
Throwable
Error Exception
RuntimeException
ArithmeticException
IOException
FileNotFoundException
Types of Exception
•Within JVM there are 2 types of exceptions▫Checked
Enforced by methods▫Unchecked
May lead to thread unraveling and poor visibility
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.
Guaranteed Execution of Cleanup Code•To write code that executes when control
leaves a code segment▫Finally
Throwing Exceptions
•Making account for an exceptional problem by throwing an exception
•The execution will not continue on current code path
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)
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().setUncaughtExceptionH
andler Globally
Thread.setDefaultUncaughtExceptionHandler
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
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.
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
Logging Events
•SLF4J▫A Simple Logging Facade for Java▫An abstraction for various logging
frameworks Java Logging API Log4j Jakarta Commons Logging
log4j
•Enabling logging at runtime•Fully Configurable at runtime via external
configuration file•Gentle learning curve•3 Main Parts
▫Loggers▫Appenders▫Layouts
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 ();
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
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
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
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
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
log4jroo
t
S X
X.Y
X.Y.Z
Console
File
log4j
Aditivity = false
root
S X
X.Y
X.Y.Z
Console
File
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]
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
Thank You