SlideShare uma empresa Scribd logo
1 de 25
Exception & Logging
Azeem Mumtaz
Software 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                  IOException




                    ArithmeticException           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().setUncaughtExceptionHandler
    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
Cons

log4j               ole


            root




        S                  X

            File



             X.Y




                          X.Y.
                           Z
Cons

log4j               ole


            root




        S                  X

            File


                            Aditivity = false
             X.Y




                          X.Y.
                           Z
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

Mais conteúdo relacionado

Mais procurados

Moldable meta-models for Moose
Moldable meta-models for MooseMoldable meta-models for Moose
Moldable meta-models for MooseESUG
 
Logging with Logback in Scala
Logging with Logback in ScalaLogging with Logback in Scala
Logging with Logback in ScalaKnoldus Inc.
 
Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924yohanbeschi
 
Plucore way of using Catalyst
Plucore way of using CatalystPlucore way of using Catalyst
Plucore way of using CatalystDaisuke Komatsu
 
No locked doors, no windows barred: hacking OpenAM infrastructure
No locked doors, no windows barred: hacking OpenAM infrastructureNo locked doors, no windows barred: hacking OpenAM infrastructure
No locked doors, no windows barred: hacking OpenAM infrastructureAndrew Petukhov
 
Running Pharo on the GemStone VM
Running Pharo on the GemStone VMRunning Pharo on the GemStone VM
Running Pharo on the GemStone VMESUG
 
Java byte code & virtual machine
Java byte code & virtual machineJava byte code & virtual machine
Java byte code & virtual machineLaxman Puri
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classesyoavwix
 
Erlang Lightning Talk
Erlang Lightning TalkErlang Lightning Talk
Erlang Lightning TalkGiltTech
 
The Real Thing: Java Virtual Machine
The Real Thing: Java Virtual MachineThe Real Thing: Java Virtual Machine
The Real Thing: Java Virtual MachineFrontech
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central DispatchRobert Brown
 
55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx FranceDavid Delabassee
 
Rational Robot (http://www.geektester.blogspot.com)
Rational Robot (http://www.geektester.blogspot.com)Rational Robot (http://www.geektester.blogspot.com)
Rational Robot (http://www.geektester.blogspot.com)raj.kamal13
 
Play Framework Logging
Play Framework LoggingPlay Framework Logging
Play Framework Loggingmitesh_sharma
 

Mais procurados (20)

Moldable meta-models for Moose
Moldable meta-models for MooseMoldable meta-models for Moose
Moldable meta-models for Moose
 
Logging with Logback in Scala
Logging with Logback in ScalaLogging with Logback in Scala
Logging with Logback in Scala
 
SLF4J+Logback
SLF4J+LogbackSLF4J+Logback
SLF4J+Logback
 
Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924
 
Plucore way of using Catalyst
Plucore way of using CatalystPlucore way of using Catalyst
Plucore way of using Catalyst
 
Log4j slideshare
Log4j slideshareLog4j slideshare
Log4j slideshare
 
No locked doors, no windows barred: hacking OpenAM infrastructure
No locked doors, no windows barred: hacking OpenAM infrastructureNo locked doors, no windows barred: hacking OpenAM infrastructure
No locked doors, no windows barred: hacking OpenAM infrastructure
 
Running Pharo on the GemStone VM
Running Pharo on the GemStone VMRunning Pharo on the GemStone VM
Running Pharo on the GemStone VM
 
Java byte code & virtual machine
Java byte code & virtual machineJava byte code & virtual machine
Java byte code & virtual machine
 
Log4j
Log4jLog4j
Log4j
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classes
 
Erlang Lightning Talk
Erlang Lightning TalkErlang Lightning Talk
Erlang Lightning Talk
 
JAVA BYTE CODE
JAVA BYTE CODEJAVA BYTE CODE
JAVA BYTE CODE
 
The Real Thing: Java Virtual Machine
The Real Thing: Java Virtual MachineThe Real Thing: Java Virtual Machine
The Real Thing: Java Virtual Machine
 
Java 2
Java 2Java 2
Java 2
 
Tools for static analyses of Java af Hans Søndergaard, ViaUC
Tools for static analyses of Java af Hans Søndergaard, ViaUCTools for static analyses of Java af Hans Søndergaard, ViaUC
Tools for static analyses of Java af Hans Søndergaard, ViaUC
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France
 
Rational Robot (http://www.geektester.blogspot.com)
Rational Robot (http://www.geektester.blogspot.com)Rational Robot (http://www.geektester.blogspot.com)
Rational Robot (http://www.geektester.blogspot.com)
 
Play Framework Logging
Play Framework LoggingPlay Framework Logging
Play Framework Logging
 

Semelhante a Logging and Exception

Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test toolsAllan Huang
 
Logging Application Behavior to MongoDB
Logging Application Behavior to MongoDBLogging Application Behavior to MongoDB
Logging Application Behavior to MongoDBRobert Stewart
 
Log4j Logging Mechanism
Log4j Logging MechanismLog4j Logging Mechanism
Log4j Logging MechanismKunal Dabir
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningMichel Schildmeijer
 
Core Java Programming Language (JSE) : Chapter I - Getting Started
Core Java Programming Language (JSE) : Chapter I - Getting StartedCore Java Programming Language (JSE) : Chapter I - Getting Started
Core Java Programming Language (JSE) : Chapter I - Getting StartedWebStackAcademy
 
Logging with Logback in Scala
Logging with Logback in ScalaLogging with Logback in Scala
Logging with Logback in ScalaKnoldus Inc.
 
Fedora Developer's Conference 2014 Talk
Fedora Developer's Conference 2014 TalkFedora Developer's Conference 2014 Talk
Fedora Developer's Conference 2014 TalkRainer Gerhards
 
Java 8 and beyond, a scala story
Java 8 and beyond, a scala storyJava 8 and beyond, a scala story
Java 8 and beyond, a scala storyittaiz
 
Log4j is a reliable, fast and flexible
Log4j is a reliable, fast and flexibleLog4j is a reliable, fast and flexible
Log4j is a reliable, fast and flexibleRamakrishna kapa
 
Apache2 BootCamp : Logging and Monitoring
Apache2 BootCamp : Logging and MonitoringApache2 BootCamp : Logging and Monitoring
Apache2 BootCamp : Logging and MonitoringWildan Maulana
 
Infinum Android Talks #14 - Log4j
Infinum Android Talks #14 - Log4jInfinum Android Talks #14 - Log4j
Infinum Android Talks #14 - Log4jInfinum
 
Application Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.keyApplication Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.keyTim Bunce
 
Application Profiling for Memory and Performance
Application Profiling for Memory and PerformanceApplication Profiling for Memory and Performance
Application Profiling for Memory and Performancepradeepfn
 

Semelhante a Logging and Exception (20)

Logging
LoggingLogging
Logging
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test tools
 
Logging Application Behavior to MongoDB
Logging Application Behavior to MongoDBLogging Application Behavior to MongoDB
Logging Application Behavior to MongoDB
 
Log4j Logging Mechanism
Log4j Logging MechanismLog4j Logging Mechanism
Log4j Logging Mechanism
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuning
 
Log4e
Log4eLog4e
Log4e
 
Core Java Programming Language (JSE) : Chapter I - Getting Started
Core Java Programming Language (JSE) : Chapter I - Getting StartedCore Java Programming Language (JSE) : Chapter I - Getting Started
Core Java Programming Language (JSE) : Chapter I - Getting Started
 
Logging with Logback in Scala
Logging with Logback in ScalaLogging with Logback in Scala
Logging with Logback in Scala
 
Log4e
Log4eLog4e
Log4e
 
Fedora Developer's Conference 2014 Talk
Fedora Developer's Conference 2014 TalkFedora Developer's Conference 2014 Talk
Fedora Developer's Conference 2014 Talk
 
Java 8 and beyond, a scala story
Java 8 and beyond, a scala storyJava 8 and beyond, a scala story
Java 8 and beyond, a scala story
 
Log4j is a reliable, fast and flexible
Log4j is a reliable, fast and flexibleLog4j is a reliable, fast and flexible
Log4j is a reliable, fast and flexible
 
Apache2 BootCamp : Logging and Monitoring
Apache2 BootCamp : Logging and MonitoringApache2 BootCamp : Logging and Monitoring
Apache2 BootCamp : Logging and Monitoring
 
Infinum Android Talks #14 - Log4j
Infinum Android Talks #14 - Log4jInfinum Android Talks #14 - Log4j
Infinum Android Talks #14 - Log4j
 
Presentation on java
Presentation  on  javaPresentation  on  java
Presentation on java
 
Application Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.keyApplication Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.key
 
FireBug And FirePHP
FireBug And FirePHPFireBug And FirePHP
FireBug And FirePHP
 
Logging with log4j v1.2
Logging with log4j v1.2Logging with log4j v1.2
Logging with log4j v1.2
 
Application Profiling for Memory and Performance
Application Profiling for Memory and PerformanceApplication Profiling for Memory and Performance
Application Profiling for Memory and Performance
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
 

Logging and Exception

  • 1. Exception & Logging Azeem Mumtaz Software Engineer
  • 2. Introduction • Why Exceptions? ▫ To describe exceptional circumstances ▫ To interrupt the current flow • In Java ▫ Exception are thrown and caught
  • 3. Exception Class Hierarchy Throwable Error Exception RuntimeException IOException ArithmeticException FileNotFoundException
  • 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
  • 21. Cons log4j ole root S X File X.Y X.Y. Z
  • 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

Notas do Editor

  1. Clean Code
  2. OutOfMemoryException
  3. UncaughtExceptions