SlideShare a Scribd company logo
1 of 35
Download to read offline
EXCEPTION HANDLING
&
LOGGING
~ BEST PRACTICES ~
Presented By

Angelin

@ardentlearner
Agenda
 Logging using Log4j
 ―Logging‖ Best Practices
 Exception Handling
 ―Exception Handling‖ Best Practices

2

@ardentlearner
Logging
using Log4j

3

@ardentlearner
Logging using Log4j
 Log4j - logging library for Java

 Logging Levels (in lowest to highest order)
 The standard levels of Log4j are ordered as
ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF

4

@ardentlearner
Logging using Log4j

Level

Description

ALL

The lowest possible rank and is intended to turn on all levels of
logging including custom levels.

TRACE

Introduced in log4j version 1.2.12, this level gives more
detailed information than the DEBUG level.

DEBUG

Designates fine-grained informational messages that are most
useful to debug an application.

INFO

Designates informational messages that highlight the progress
of the application at coarse-grained level.

5

@ardentlearner
Logging using Log4j

Level

Description

WARN

Designates potentially harmful situations. This level can be
used to warn usage of deprecated APIs, poor use of API,
‗almost‘ errors and other runtime situations that are
undesirable or unexpected, but not necessarily ―wrong‖.

ERROR

Designates error events that might still allow the application to
continue running. This level can be used to inform about a
serious error which needs to be addressed and may result in
unstable state.

FATAL

Designates very severe error events that will presumably lead
the application to abort.

OFF

The highest possible rank and is intended to turn off logging.

6

@ardentlearner
How Logging Level works ?
A logging request of a particular level is said to be enabled if that
level is higher than or equal to the level of its logger.
Example
import org.apache.log4j.Logger;
public class LogClass {
private static final Logger LOGGER = Logger.getLogger(LogClass.class);
public static void main(String[] args) {
LOGGER.setLevel(Level.WARN);
LOGGER.trace("Trace Message!");
LOGGER.debug("Debug Message!");
LOGGER.info("Info Message!");
LOGGER.warn("Warn Message!");
LOGGER.error("Error Message!");
LOGGER.fatal("Fatal Message!");
}

Output:
Warn Message!
Error Message!
Fatal Message!

}
7

@ardentlearner
―Logging‖
BEST PRACTICES

8

@ardentlearner
Logging - Best Practices
 Declare the logger to be both static and final to ensure that every
instance of a class shares the common logger object.
 Add code to check whether logging has been enabled at the right level.

 Use meaningful log messages that are relevant to the context.
 Better to use logging only to log the following,
• method entry (optionally with the method‘s input parameter values)
• method exit
• root cause message of exceptions that are handled at the
exception‘s origin point.

9

@ardentlearner
Logging - Best Practices
 Any other intermediate redundant logging statements, which are used
just for the purpose of debugging can still be avoided.
Example
try {
LOGGER.debug(“About to enter getItemDescription method”);
// The above logging statement is not required,
// if getItemDescription() method logs its method entry

String itemDesc = getItemDescription(itemNumber);
LOGGER.debug(“Exited getItemDescription method”);
// The above logging statement is not required,
// if getItemDescription() method logs its method exit
} catch (ApplicationCustomException ace) {
LOGGER.error(ace.getErrorMessage());
throw se;
}

10

@ardentlearner
Logging - Best Practices
 Avoid logging at ‗every‘ place where a custom exception is thrown.
Instead log the custom exception‘s message in its ‗catch‘ handler.
Example
try {
if (null == itemNumber || itemNumber.isEmpty()) {

LOGGER.error(“Item number is invalid”);
// The above logging statement is not required,
// since the catch handler logs the message
// passed through the ApplicationCustomException thrown
throw new ApplicationCustomException(“Item number is invalid”);
}
……
……

11

@ardentlearner
Logging - Best Practices
try {
item = Integer.parseInt(itemNumber);

} catch (NumberFormatException nfe) {
LOGGER.error(“Item number is invalid and not a number”);
// The above logging statement is not required,
// since the catch handler logs the message
// passed through the ApplicationCustomException thrown

throw new ApplicationCustomException(“Item number is invalid and
not a number”, nfe);
}
……
} catch (ApplicationCustomException ace) {

LOGGER.error(ace.getErrorMessage());
throw ace;
}
12

@ardentlearner
Exception Handling

13

@ardentlearner
Exception
 Exception
An exception is an object that represents an abnormal event.
When one method (caller) calls another method (callee), they may
communicate about what happened via an exception.
 Types of Exception
When one method throws an exception, that exception can be
either a checked exception or an unchecked exception.
Throwable

Error

Exception

RuntimeException
Unchecked

Checked

Unchecked
14

@ardentlearner
Exception related terminologies
 A method may not handle exceptions thrown within it and would
instead throw it up the method call stack to let its caller know that an
abnormal event occurred. It does so by declaring that exception in the
throws clause of its declaration. This is called ‗ducking‘.
 The caller itself may handle the exception thrown by its callee or in
turn propagate that to its own caller. This is also called ‗ducking‘.

 A method may translate an exception thrown by its callee into another
exception and throw the new exception (to its own caller).

15

@ardentlearner
―Exception Handling‖
BEST PRACTICES

16

@ardentlearner
Exception Handling - Best Practice #1
 Handle Exceptions close to its origin
 Does NOT mean ―catch and swallow‖ (i.e. suppress or ignore
exceptions)
Example
try {
// code that is capable of throwing a XyzException
} catch (XyzException e) {
// do nothing or simply log and proceed
}

 It means, ―log and handle the exception right there‖ or ―log and
throw the exception up the method call stack using a custom
exception relevant to that source layer‖ and let it be handled later
by a method up the call stack.
– DAO layer – DataAccessException
– Business layer – Application‘s Custom Exception (example SKUException)

17

@ardentlearner
Exception Handling - Best Practice #1 (Contd..)
Note

The approach ―log and handle the exception right there‖ makes
way to use the specific exception type to differentiate exceptions and
handle exceptions in some explicit manner.
The approach ―log and throw the exception up the method call
stack using a custom exception relevant to that source layer‖ – makes
way for creation of groups of exceptions and handling exceptions in a
generic manner.

18

@ardentlearner
Exception Handling - Best Practice #1 (Contd..)
Note

When catching an exception and throwing it using an exception
relevant to that source layer, make sure to use the construct that
passes the original exception‘s cause. This will help preserve the
original root cause of the exception.
try {
// code that is capable of throwing a SQLException
} catch (SQLException e) {
// log technical SQL Error messages, but do not pass
// it to the client. Use user-friendly message instead

LOGGER.error(“An error occurred when searching for the SKU
details” + e.getMessage());
throw new DataAccessException(“An error occurred when searching
for the SKU details”, e);
}
19

@ardentlearner
Exception Handling - Best Practice #2
 Log Exceptions just once and log it close to its origin
Logging the same exception stack trace more than once can confuse
the programmer examining the stack trace about the original source
of exception. So, log Exceptions just once and log it close to its origin.

try {
// Code that is capable of throwing a XyzException
} catch (XyzException e) {

// Log the exception specific information.
// Throw exception relevant to that source layer
}

20

@ardentlearner
Exception Handling - Best Practice #2 (Contd..)
Note
There is an exception to this rule, in case of existing code that
may not have logged the exception details at its origin.
In such cases, it would be required to log the exception details
in the first method up the call stack that handles that exception. But
care should be taken NOT to COMPLETELY overwrite the original
exception‘s message with some other message when logging.
Example
DAO Layer:
try {
// code that is capable of throwing a SQLException
} catch (SQLException e) {
// Note that LOGGING has been missed here
throw new DataAccessException(“An error occurred when
processing the query.”, e);
}
21

@ardentlearner
Exception Handling - Best Practice #2 (Contd..)
Since logging was missed in the exception handler of the DAO layer,
it is mandated in the exception handler of the next enclosing layer –
in this example it is the (Business/Processor) layer.
Business/Processor Layer:
try {
// code that is capable of throwing a DataAccessException
} catch (DataAccessException e) {
// logging is mandated here as it was not logged
// at its source (DAO layer method)
LOGGER.error(e.getMessage());
throw new SKUException(e.getMessage(), e);
}

22

@ardentlearner
Exception Handling - Best Practice #3
 Do not catch “Exception”
Accidentally swallowing RuntimeException
try {
doSomething();
} catch (Exception e) {
LOGGER.error(e.getMessage());
}

This code
 also captures any RuntimeExceptions that might have been thrown
by doSomething,
 ignores unchecked exceptions and
 prevents them from being propagated.
So, all checked exceptions should be caught and handled using
appropriate catch handlers. And the exceptions should be logged and
thrown to the outermost layer (i.e. the method at the top of the
calling stack) using application specific custom exceptions relevant to
that source layer.
23

@ardentlearner
Exception Handling - Best Practice #4
 Handle Exceptions before sending response to Client
The layer of code component (i.e. the method at the top of the

calling stack) that sends back response to the client, has to do the
following:
 catch ALL checked exceptions and handle them by creating proper
error response and send it back to client.
 NOT allow any checked exception to be ―thrown‖ to the client.

 handle the Business layer exception and all other checked
exceptions raised from within the code in that layer separately.
Examples of such components are:

 Service layer Classes in Web Service based applications
 Action Classes in Struts framework based applications
24

@ardentlearner
Exception Handling - Best Practice #4 (Contd..)
Example
try {
// Code that is capable of throwing a SKUException
// (a custom exception in this sample application)
} catch (SKUException e) {
// Form error response using the exception‟s data,
// error code and/or error message

}

25

@ardentlearner
Exception Handling - Best Practice #4 (Contd..)
An exception to handling „Exception‟ – Case 1
There would be situations (although rarely) where the users
would prefer a user-friendly/easy to understand message to be
shown to them, instead of the system defined messages thrown by
unrecoverable exceptions.
In such cases, the method at the top of the calling stack,
which is part of the code that sends response to the client is
expected to handle all unchecked exceptions thrown from within the
‗try‘ block.
By doing this, technical exception messages can be replaced
with generic messages that the user can understand. So, a catch
handler for ‗Exception‘ can be placed in it.
This is an exception to best practice #3 and is only for the
outermost layer. In other layers downstream in the layered
architecture, catching ‗Exception‘ is not recommended for reasons
explained under best practice #3.

26

@ardentlearner
Exception Handling - Best Practice #4 (Contd..)
Example
try {
// Code that is capable of throwing a SKUException
// (a custom exception in this example application)
} catch (SKUException e) {
// Form error response using the exception‟s data,
// error code and/or error message
} catch (Exception e) {

//
//
//
//
//

Log the exception related message here, since this block is
expected to get only the unchecked exceptions
that had not been captured and logged elsewhere in the code,
provided the exception handling and logging are properly
handled at the other layers in the layered architecture.

// Form error response using the exception‟s data,
// error code and/or error message
}
27

@ardentlearner
Exception Handling - Best Practice #4 (Contd..)
An exception to handling „Exception‟ – Case 2
Certain other exceptional cases justify when it is handy and
required to catch generic Exceptions. These cases are very specific
but important to large, failure-tolerant systems.
Consider a request processing system that reads requests
from a queue of requests and processes them in order.
public void processAllRequests() {
Request req = null;
try {
while (true) {
req = getNextRequest();
if (req != null) {
processRequest(req); // throws BadRequestException
} else { // Request queue is empty, must be done
break;
}
}
} catch (BadRequestException e) {
log.error(”Invalid request:” + req, e);
}
}
28

@ardentlearner
Exception Handling - Best Practice #4 (Contd..)
An exception to handling „Exception‟ – Case 2 (Contd..)
With the above code, if any exception occurs while the
request is being processed (either
a BadRequestException or any subclass of RuntimeException
including NullPointerException), then that exception will be
caught outside the processing ‗while‘ loop.
So, any error causes the processing loop to stop and any
remaining requests will not be processed. That represents a poor way
of handling an error during request processing.
A better way to handle request processing is to make two
significant changes to the logic.
1) Move the try/catch block inside the request-processing loop. That
way, any errors are caught and handled inside the processing loop,
and they do not cause the loop to break. Thus, the loop continues to
process requests, even when a single request fails.
2) Change the try/catch block to catch a generic Exception,
so any exception is caught inside the loop and requests continue to
process.
29

@ardentlearner
Exception Handling - Best Practice #4 (Contd..)
An exception to handling „Exception‟ – Case 2 (Contd..)
public void processAllRequests() {
while (true) {
Request req = null;
try {
req = getNextRequest();
if (req != null) {
processRequest(req); // throws BadRequestException
} else { // Request queue is empty, must be done
break;
}
} catch (BadRequestException e) {
log.error(”Invalid request:” + req, e);
}
}
}

30

@ardentlearner
Exception Handling - Best Practice #4 (Contd..)
An exception to handling „Exception‟ – Case 2 (Contd..)
Catching a generic Exception sounds like a direct violation of
the maxim suggested in best practice #3 —and it is. But the
circumstance discussed is a specific and special one. In this case,
the generic Exception is being caught to prevent a single exception
from stopping an entire system.
In situations where requests, transactions or events are
being processed in a loop, that loop needs to continue to process
even when exceptions are thrown during processing.

31

@ardentlearner
Exception Handling - Best Practice #5
 Handling common Runtime Exceptions
 NullPointerException
• It is the developer‘s responsibility to ensure that no code can throw it.
• Run CodePro and add null reference checks wherever it has been missed.

 NumberFormatException, ParseException
Catch these and create new exceptions specific to the layer from which it
is thrown (usually from business layer) using user-friendly and non
technical messages.

 To avoid ClassCastException, check the type of the class to be cast
using the instanceof operator before casting.
 To avoid IndexOutOfBoundsException, check the length of the array
before trying to work with an element of it.
 To avoid ArithmeticException, make sure that the divisor is not zero
before computing the division.
32

@ardentlearner
Exception Handling - Best Practice #5 (Contd..)
 Example
try {

int item = Integer.parseInt(itemNumber);
} catch (NumberFormatException nfe) {
LOGGER.error("SKU number is invalid and not a number");
throw new SKUException("SKU number is invalid and not a number",
nfe);
}

 All other unchecked exceptions (RuntimeExceptions) will be caught and
handled by the ‗Exception‘ handler in the outermost layer (as explained
in Best Practice #4 - Case 1).
33

@ardentlearner
Exception Handling - Best Practice #6
 Document Exceptions Thrown in Javadoc
For each method that throws checked exceptions, document each
exception thrown with a @throws tag in its Javadoc, including the
condition under which the exception is thrown.

34

@ardentlearner
THANK YOU

35

@ardentlearner

More Related Content

What's hot

MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring Data
Anton Sulzhenko
 

What's hot (20)

KSQL Performance Tuning for Fun and Profit ( Nick Dearden, Confluent) Kafka S...
KSQL Performance Tuning for Fun and Profit ( Nick Dearden, Confluent) Kafka S...KSQL Performance Tuning for Fun and Profit ( Nick Dearden, Confluent) Kafka S...
KSQL Performance Tuning for Fun and Profit ( Nick Dearden, Confluent) Kafka S...
 
Application Load Balancer and the integration with AutoScaling and ECS - Pop-...
Application Load Balancer and the integration with AutoScaling and ECS - Pop-...Application Load Balancer and the integration with AutoScaling and ECS - Pop-...
Application Load Balancer and the integration with AutoScaling and ECS - Pop-...
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring Data
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
LMAX Disruptor - High Performance Inter-Thread Messaging Library
LMAX Disruptor - High Performance Inter-Thread Messaging LibraryLMAX Disruptor - High Performance Inter-Thread Messaging Library
LMAX Disruptor - High Performance Inter-Thread Messaging Library
 
Présentation Oracle DataBase 11g
Présentation Oracle DataBase 11gPrésentation Oracle DataBase 11g
Présentation Oracle DataBase 11g
 
Spring @Transactional Explained
Spring @Transactional ExplainedSpring @Transactional Explained
Spring @Transactional Explained
 
Concurrency With Go
Concurrency With GoConcurrency With Go
Concurrency With Go
 
An introduction to terraform
An introduction to terraformAn introduction to terraform
An introduction to terraform
 
Quarkus k8s
Quarkus   k8sQuarkus   k8s
Quarkus k8s
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
Nginx Reverse Proxy with Kafka.pptx
Nginx Reverse Proxy with Kafka.pptxNginx Reverse Proxy with Kafka.pptx
Nginx Reverse Proxy with Kafka.pptx
 
Spring integration
Spring integrationSpring integration
Spring integration
 
Oracle RAC 19c - the Basis for the Autonomous Database
Oracle RAC 19c - the Basis for the Autonomous DatabaseOracle RAC 19c - the Basis for the Autonomous Database
Oracle RAC 19c - the Basis for the Autonomous Database
 
Oracle 21c: New Features and Enhancements of Data Pump & TTS
Oracle 21c: New Features and Enhancements of Data Pump & TTSOracle 21c: New Features and Enhancements of Data Pump & TTS
Oracle 21c: New Features and Enhancements of Data Pump & TTS
 
Step by Step to Install oracle grid 11.2.0.3 on solaris 11.1
Step by Step to Install oracle grid 11.2.0.3 on solaris 11.1Step by Step to Install oracle grid 11.2.0.3 on solaris 11.1
Step by Step to Install oracle grid 11.2.0.3 on solaris 11.1
 
Oracle Flex ASM - What’s New and Best Practices by Jim Williams
Oracle Flex ASM - What’s New and Best Practices by Jim WilliamsOracle Flex ASM - What’s New and Best Practices by Jim Williams
Oracle Flex ASM - What’s New and Best Practices by Jim Williams
 
Oracle sql high performance tuning
Oracle sql high performance tuningOracle sql high performance tuning
Oracle sql high performance tuning
 
Avro
AvroAvro
Avro
 
Oracle Security Presentation
Oracle Security PresentationOracle Security Presentation
Oracle Security Presentation
 

Similar to Exception handling & logging in Java - Best Practices (Updated)

Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practices
Angelin R
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
Vince Vo
 
Exception Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLRException Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLR
Kiran Munir
 

Similar to Exception handling & logging in Java - Best Practices (Updated) (20)

Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practices
 
Java Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and LoggingJava Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and Logging
 
Exceptions
ExceptionsExceptions
Exceptions
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation Controls
 
Exceptions
ExceptionsExceptions
Exceptions
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exception
ExceptionException
Exception
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Best Coding Practices For Android Application Development
Best Coding Practices For Android Application DevelopmentBest Coding Practices For Android Application Development
Best Coding Practices For Android Application Development
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
Exception Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLRException Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLR
 

More from Angelin R

Agile SCRUM Methodology
Agile SCRUM MethodologyAgile SCRUM Methodology
Agile SCRUM Methodology
Angelin R
 
Tamil Christian Worship Songs
Tamil Christian Worship SongsTamil Christian Worship Songs
Tamil Christian Worship Songs
Angelin R
 

More from Angelin R (16)

Comparison of Java Web Application Frameworks
Comparison of Java Web Application FrameworksComparison of Java Web Application Frameworks
Comparison of Java Web Application Frameworks
 
[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQube[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQube
 
Java Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQubeJava Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQube
 
The principles of good programming
The principles of good programmingThe principles of good programming
The principles of good programming
 
A Slice of Me
A Slice of MeA Slice of Me
A Slice of Me
 
Team Leader - 30 Essential Traits
Team Leader - 30 Essential TraitsTeam Leader - 30 Essential Traits
Team Leader - 30 Essential Traits
 
Action Script
Action ScriptAction Script
Action Script
 
Agile SCRUM Methodology
Agile SCRUM MethodologyAgile SCRUM Methodology
Agile SCRUM Methodology
 
Tamil Christian Worship Songs
Tamil Christian Worship SongsTamil Christian Worship Songs
Tamil Christian Worship Songs
 
Flex MXML Programming
Flex MXML ProgrammingFlex MXML Programming
Flex MXML Programming
 
Introduction to Adobe Flex
Introduction to Adobe FlexIntroduction to Adobe Flex
Introduction to Adobe Flex
 
Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)
 
Restful Web Services
Restful Web ServicesRestful Web Services
Restful Web Services
 
Effective Team Work Model
Effective Team Work ModelEffective Team Work Model
Effective Team Work Model
 
Team Building Activities
Team Building ActivitiesTeam Building Activities
Team Building Activities
 
XStream
XStreamXStream
XStream
 

Recently uploaded

Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 

Recently uploaded (20)

What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
Oauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoftOauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoft
 
Your enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jYour enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4j
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
BT & Neo4j _ How Knowledge Graphs help BT deliver Digital Transformation.pptx
BT & Neo4j _ How Knowledge Graphs help BT deliver Digital Transformation.pptxBT & Neo4j _ How Knowledge Graphs help BT deliver Digital Transformation.pptx
BT & Neo4j _ How Knowledge Graphs help BT deliver Digital Transformation.pptx
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 

Exception handling & logging in Java - Best Practices (Updated)

  • 1. EXCEPTION HANDLING & LOGGING ~ BEST PRACTICES ~ Presented By Angelin @ardentlearner
  • 2. Agenda  Logging using Log4j  ―Logging‖ Best Practices  Exception Handling  ―Exception Handling‖ Best Practices 2 @ardentlearner
  • 4. Logging using Log4j  Log4j - logging library for Java  Logging Levels (in lowest to highest order)  The standard levels of Log4j are ordered as ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF 4 @ardentlearner
  • 5. Logging using Log4j Level Description ALL The lowest possible rank and is intended to turn on all levels of logging including custom levels. TRACE Introduced in log4j version 1.2.12, this level gives more detailed information than the DEBUG level. DEBUG Designates fine-grained informational messages that are most useful to debug an application. INFO Designates informational messages that highlight the progress of the application at coarse-grained level. 5 @ardentlearner
  • 6. Logging using Log4j Level Description WARN Designates potentially harmful situations. This level can be used to warn usage of deprecated APIs, poor use of API, ‗almost‘ errors and other runtime situations that are undesirable or unexpected, but not necessarily ―wrong‖. ERROR Designates error events that might still allow the application to continue running. This level can be used to inform about a serious error which needs to be addressed and may result in unstable state. FATAL Designates very severe error events that will presumably lead the application to abort. OFF The highest possible rank and is intended to turn off logging. 6 @ardentlearner
  • 7. How Logging Level works ? A logging request of a particular level is said to be enabled if that level is higher than or equal to the level of its logger. Example import org.apache.log4j.Logger; public class LogClass { private static final Logger LOGGER = Logger.getLogger(LogClass.class); public static void main(String[] args) { LOGGER.setLevel(Level.WARN); LOGGER.trace("Trace Message!"); LOGGER.debug("Debug Message!"); LOGGER.info("Info Message!"); LOGGER.warn("Warn Message!"); LOGGER.error("Error Message!"); LOGGER.fatal("Fatal Message!"); } Output: Warn Message! Error Message! Fatal Message! } 7 @ardentlearner
  • 9. Logging - Best Practices  Declare the logger to be both static and final to ensure that every instance of a class shares the common logger object.  Add code to check whether logging has been enabled at the right level.  Use meaningful log messages that are relevant to the context.  Better to use logging only to log the following, • method entry (optionally with the method‘s input parameter values) • method exit • root cause message of exceptions that are handled at the exception‘s origin point. 9 @ardentlearner
  • 10. Logging - Best Practices  Any other intermediate redundant logging statements, which are used just for the purpose of debugging can still be avoided. Example try { LOGGER.debug(“About to enter getItemDescription method”); // The above logging statement is not required, // if getItemDescription() method logs its method entry String itemDesc = getItemDescription(itemNumber); LOGGER.debug(“Exited getItemDescription method”); // The above logging statement is not required, // if getItemDescription() method logs its method exit } catch (ApplicationCustomException ace) { LOGGER.error(ace.getErrorMessage()); throw se; } 10 @ardentlearner
  • 11. Logging - Best Practices  Avoid logging at ‗every‘ place where a custom exception is thrown. Instead log the custom exception‘s message in its ‗catch‘ handler. Example try { if (null == itemNumber || itemNumber.isEmpty()) { LOGGER.error(“Item number is invalid”); // The above logging statement is not required, // since the catch handler logs the message // passed through the ApplicationCustomException thrown throw new ApplicationCustomException(“Item number is invalid”); } …… …… 11 @ardentlearner
  • 12. Logging - Best Practices try { item = Integer.parseInt(itemNumber); } catch (NumberFormatException nfe) { LOGGER.error(“Item number is invalid and not a number”); // The above logging statement is not required, // since the catch handler logs the message // passed through the ApplicationCustomException thrown throw new ApplicationCustomException(“Item number is invalid and not a number”, nfe); } …… } catch (ApplicationCustomException ace) { LOGGER.error(ace.getErrorMessage()); throw ace; } 12 @ardentlearner
  • 14. Exception  Exception An exception is an object that represents an abnormal event. When one method (caller) calls another method (callee), they may communicate about what happened via an exception.  Types of Exception When one method throws an exception, that exception can be either a checked exception or an unchecked exception. Throwable Error Exception RuntimeException Unchecked Checked Unchecked 14 @ardentlearner
  • 15. Exception related terminologies  A method may not handle exceptions thrown within it and would instead throw it up the method call stack to let its caller know that an abnormal event occurred. It does so by declaring that exception in the throws clause of its declaration. This is called ‗ducking‘.  The caller itself may handle the exception thrown by its callee or in turn propagate that to its own caller. This is also called ‗ducking‘.  A method may translate an exception thrown by its callee into another exception and throw the new exception (to its own caller). 15 @ardentlearner
  • 17. Exception Handling - Best Practice #1  Handle Exceptions close to its origin  Does NOT mean ―catch and swallow‖ (i.e. suppress or ignore exceptions) Example try { // code that is capable of throwing a XyzException } catch (XyzException e) { // do nothing or simply log and proceed }  It means, ―log and handle the exception right there‖ or ―log and throw the exception up the method call stack using a custom exception relevant to that source layer‖ and let it be handled later by a method up the call stack. – DAO layer – DataAccessException – Business layer – Application‘s Custom Exception (example SKUException) 17 @ardentlearner
  • 18. Exception Handling - Best Practice #1 (Contd..) Note The approach ―log and handle the exception right there‖ makes way to use the specific exception type to differentiate exceptions and handle exceptions in some explicit manner. The approach ―log and throw the exception up the method call stack using a custom exception relevant to that source layer‖ – makes way for creation of groups of exceptions and handling exceptions in a generic manner. 18 @ardentlearner
  • 19. Exception Handling - Best Practice #1 (Contd..) Note When catching an exception and throwing it using an exception relevant to that source layer, make sure to use the construct that passes the original exception‘s cause. This will help preserve the original root cause of the exception. try { // code that is capable of throwing a SQLException } catch (SQLException e) { // log technical SQL Error messages, but do not pass // it to the client. Use user-friendly message instead LOGGER.error(“An error occurred when searching for the SKU details” + e.getMessage()); throw new DataAccessException(“An error occurred when searching for the SKU details”, e); } 19 @ardentlearner
  • 20. Exception Handling - Best Practice #2  Log Exceptions just once and log it close to its origin Logging the same exception stack trace more than once can confuse the programmer examining the stack trace about the original source of exception. So, log Exceptions just once and log it close to its origin. try { // Code that is capable of throwing a XyzException } catch (XyzException e) { // Log the exception specific information. // Throw exception relevant to that source layer } 20 @ardentlearner
  • 21. Exception Handling - Best Practice #2 (Contd..) Note There is an exception to this rule, in case of existing code that may not have logged the exception details at its origin. In such cases, it would be required to log the exception details in the first method up the call stack that handles that exception. But care should be taken NOT to COMPLETELY overwrite the original exception‘s message with some other message when logging. Example DAO Layer: try { // code that is capable of throwing a SQLException } catch (SQLException e) { // Note that LOGGING has been missed here throw new DataAccessException(“An error occurred when processing the query.”, e); } 21 @ardentlearner
  • 22. Exception Handling - Best Practice #2 (Contd..) Since logging was missed in the exception handler of the DAO layer, it is mandated in the exception handler of the next enclosing layer – in this example it is the (Business/Processor) layer. Business/Processor Layer: try { // code that is capable of throwing a DataAccessException } catch (DataAccessException e) { // logging is mandated here as it was not logged // at its source (DAO layer method) LOGGER.error(e.getMessage()); throw new SKUException(e.getMessage(), e); } 22 @ardentlearner
  • 23. Exception Handling - Best Practice #3  Do not catch “Exception” Accidentally swallowing RuntimeException try { doSomething(); } catch (Exception e) { LOGGER.error(e.getMessage()); } This code  also captures any RuntimeExceptions that might have been thrown by doSomething,  ignores unchecked exceptions and  prevents them from being propagated. So, all checked exceptions should be caught and handled using appropriate catch handlers. And the exceptions should be logged and thrown to the outermost layer (i.e. the method at the top of the calling stack) using application specific custom exceptions relevant to that source layer. 23 @ardentlearner
  • 24. Exception Handling - Best Practice #4  Handle Exceptions before sending response to Client The layer of code component (i.e. the method at the top of the calling stack) that sends back response to the client, has to do the following:  catch ALL checked exceptions and handle them by creating proper error response and send it back to client.  NOT allow any checked exception to be ―thrown‖ to the client.  handle the Business layer exception and all other checked exceptions raised from within the code in that layer separately. Examples of such components are:  Service layer Classes in Web Service based applications  Action Classes in Struts framework based applications 24 @ardentlearner
  • 25. Exception Handling - Best Practice #4 (Contd..) Example try { // Code that is capable of throwing a SKUException // (a custom exception in this sample application) } catch (SKUException e) { // Form error response using the exception‟s data, // error code and/or error message } 25 @ardentlearner
  • 26. Exception Handling - Best Practice #4 (Contd..) An exception to handling „Exception‟ – Case 1 There would be situations (although rarely) where the users would prefer a user-friendly/easy to understand message to be shown to them, instead of the system defined messages thrown by unrecoverable exceptions. In such cases, the method at the top of the calling stack, which is part of the code that sends response to the client is expected to handle all unchecked exceptions thrown from within the ‗try‘ block. By doing this, technical exception messages can be replaced with generic messages that the user can understand. So, a catch handler for ‗Exception‘ can be placed in it. This is an exception to best practice #3 and is only for the outermost layer. In other layers downstream in the layered architecture, catching ‗Exception‘ is not recommended for reasons explained under best practice #3. 26 @ardentlearner
  • 27. Exception Handling - Best Practice #4 (Contd..) Example try { // Code that is capable of throwing a SKUException // (a custom exception in this example application) } catch (SKUException e) { // Form error response using the exception‟s data, // error code and/or error message } catch (Exception e) { // // // // // Log the exception related message here, since this block is expected to get only the unchecked exceptions that had not been captured and logged elsewhere in the code, provided the exception handling and logging are properly handled at the other layers in the layered architecture. // Form error response using the exception‟s data, // error code and/or error message } 27 @ardentlearner
  • 28. Exception Handling - Best Practice #4 (Contd..) An exception to handling „Exception‟ – Case 2 Certain other exceptional cases justify when it is handy and required to catch generic Exceptions. These cases are very specific but important to large, failure-tolerant systems. Consider a request processing system that reads requests from a queue of requests and processes them in order. public void processAllRequests() { Request req = null; try { while (true) { req = getNextRequest(); if (req != null) { processRequest(req); // throws BadRequestException } else { // Request queue is empty, must be done break; } } } catch (BadRequestException e) { log.error(”Invalid request:” + req, e); } } 28 @ardentlearner
  • 29. Exception Handling - Best Practice #4 (Contd..) An exception to handling „Exception‟ – Case 2 (Contd..) With the above code, if any exception occurs while the request is being processed (either a BadRequestException or any subclass of RuntimeException including NullPointerException), then that exception will be caught outside the processing ‗while‘ loop. So, any error causes the processing loop to stop and any remaining requests will not be processed. That represents a poor way of handling an error during request processing. A better way to handle request processing is to make two significant changes to the logic. 1) Move the try/catch block inside the request-processing loop. That way, any errors are caught and handled inside the processing loop, and they do not cause the loop to break. Thus, the loop continues to process requests, even when a single request fails. 2) Change the try/catch block to catch a generic Exception, so any exception is caught inside the loop and requests continue to process. 29 @ardentlearner
  • 30. Exception Handling - Best Practice #4 (Contd..) An exception to handling „Exception‟ – Case 2 (Contd..) public void processAllRequests() { while (true) { Request req = null; try { req = getNextRequest(); if (req != null) { processRequest(req); // throws BadRequestException } else { // Request queue is empty, must be done break; } } catch (BadRequestException e) { log.error(”Invalid request:” + req, e); } } } 30 @ardentlearner
  • 31. Exception Handling - Best Practice #4 (Contd..) An exception to handling „Exception‟ – Case 2 (Contd..) Catching a generic Exception sounds like a direct violation of the maxim suggested in best practice #3 —and it is. But the circumstance discussed is a specific and special one. In this case, the generic Exception is being caught to prevent a single exception from stopping an entire system. In situations where requests, transactions or events are being processed in a loop, that loop needs to continue to process even when exceptions are thrown during processing. 31 @ardentlearner
  • 32. Exception Handling - Best Practice #5  Handling common Runtime Exceptions  NullPointerException • It is the developer‘s responsibility to ensure that no code can throw it. • Run CodePro and add null reference checks wherever it has been missed.  NumberFormatException, ParseException Catch these and create new exceptions specific to the layer from which it is thrown (usually from business layer) using user-friendly and non technical messages.  To avoid ClassCastException, check the type of the class to be cast using the instanceof operator before casting.  To avoid IndexOutOfBoundsException, check the length of the array before trying to work with an element of it.  To avoid ArithmeticException, make sure that the divisor is not zero before computing the division. 32 @ardentlearner
  • 33. Exception Handling - Best Practice #5 (Contd..)  Example try { int item = Integer.parseInt(itemNumber); } catch (NumberFormatException nfe) { LOGGER.error("SKU number is invalid and not a number"); throw new SKUException("SKU number is invalid and not a number", nfe); }  All other unchecked exceptions (RuntimeExceptions) will be caught and handled by the ‗Exception‘ handler in the outermost layer (as explained in Best Practice #4 - Case 1). 33 @ardentlearner
  • 34. Exception Handling - Best Practice #6  Document Exceptions Thrown in Javadoc For each method that throws checked exceptions, document each exception thrown with a @throws tag in its Javadoc, including the condition under which the exception is thrown. 34 @ardentlearner