SlideShare a Scribd company logo
EXCEPTION
HANDLING
&
LOGGING
BEST PRACTICES
Angelin
AGENDA
Logging using Log4j

“Logging” Best Practices
“Exception Handling” Best Practices
CodePro Errors and Fixes
Logging using Log4j
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
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.

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”.
Logging using Log4j
Level

Description

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.
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.*;
public class LogClass {
private static final org.apache.log4j.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!
“Logging”
BEST PRACTICES
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.
Logging - Best Practices
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.
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 getSkuDescription method”);
// The above logging statement is not required,
// if getSkuDescription() method logs its method entry
String skuDesc = getSkuDescription(skuNumber);
LOGGER.debug(“Exited getSkuDescription method”);
// The above logging statement is not required,
// if getSkuDescription() method logs its method exit
} catch (ServiceException se) {
LOGGER.error(se.getErrorMessage());
throw se;
}
Logging - Best Practices
Avoid logging at ‘every’ place where a custom exception is
thrown and instead log the custom exceptions’ message
in its ‘catch’ handler.
Example
try {
if (null == skuNumber || skuNumber.isEmpty()) {
LOGGER.error(“Sku number is invalid”);
// The above logging statement is not required,
// since the catch handler logs the message
throw new ServiceException(“Sku number is invalid”);
}
Logging - Best Practices
try {

sku = Integer.parseInt(skuNumber);
} catch (NumberFormatException nfe) {
LOGGER.error(“Sku number is invalid and not a number”);
// The above logging statement is not required,
// since the catch handler logs the message
throw new ServiceException(“Sku number is invalid and
not a number”, nfe);
}
……
} catch (ServiceException se) {
LOGGER.error(se.getErrorMessage());
throw se;
}
Exception handling
Best Practices
Exception Handling - Best Practice #1
Handle Exceptions close to its origin
 Does NOT mean “catch and swallow” (i.e. suppress or ignore
exceptions)
try {
// code that is capable of throwing a XyzException
} catch ( XyzException e) {
// do nothing or simply log and proceed
}
 It means, “log and throw an exception relevant to that source
layer”
– DAO layer - DataAccessException
– Business layer - ApplicationException (example OUSException)
Exception Handling - Best Practice #1
Important Note
In applications using Web Services, the Web Service (a.k.a
Resource) layer,
 should catch ALL exceptions and handle them by creating proper

error response and send it back to client.
 should NOT allow any exception (checked or unchecked) to be
“thrown” to client.
 should handle the Business layer exception and all other
unchecked exceptions separately.
Exception Handling - Best Practice #1
Example
try {
// code that is capable of throwing an ApplicationException
} catch (ApplicationException 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.
// form error response using the exception’s
// data – error code and/or error message
}
The catch handler for ‘Exception’ in the Web Service layer is expected to
handle all unchecked exceptions thrown from within ‘try’ block
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.
try {
// code that is capable of throwing a XyzException
} catch (XyzException e) {
// log the exception specific information
// throw exception relevant to that source layer
}
Exception Handling - Best Practice #2
#1 - When catching an exception and throwing it through an
exception relevant to that source layer, make sure to use the
construct that passes the original exception’s cause. Otherwise,
CodePro will report "No cause specified when creating 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);
}
Exception Handling - Best Practice #2
#2 - 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) {
// LOGGING missed here
throw new DataAccessException(“An error occurred
when processing the query.”, e);
}
Exception Handling - Best Practice #2
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 OUSException(e.getMessage(), e);
}
Exception Handling - Best Practice #3
Do not catch “Exception”
Accidentally swallowing RuntimeException
try {
doSomething();
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
This code
1. also captures any RuntimeExceptions that might have been
thrown by doSomething,
2. ignores unchecked exceptions and
3. prevents them from being propagated.
Exception Handling - Best Practice #3
Important Note (about some common RuntimeExceptions)
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.
Exception Handling - Best Practice #3
Important Note (about some common RuntimeExceptions)
Example
try {
int sku = Integer.parseInt(skuNumber);
} catch (NumberFormatException nfe) {
LOGGER.error("SKU number is invalid and not a number");
throw new OUSException("SKU number is invalid and not a
number", nfe);
}
All other unchecked exceptions (RuntimeExceptions) will be
caught and handled by the Web Service layer (as explained in Best
Practice #1).
CODEPRO
Errors & fixes
Fix to common CodePro errors
"Invalid exception parameter name"
Solution
Rename the parameter to “e”
Example
try {
// code that is capable of throwing a DataAccessException
} catch (DataAccessException e) {
throw new OUSException(e.getMessage(), e);
}
Fix to common CodePro errors
"No cause specified when creating exception" when wrapping
an exception into another exception.
Solution
Use the construct that passes the original exception’s cause
Example
try {
// code that is capable of throwing a SQLException
} catch (SQLException e) {
LOGGER.error(e.getMessage());
throw new DataAccessException(“An error occurred
when searching for the SKU details”, e);
}
THANK YOU

More Related Content

What's hot (20)

PPTX
File upload vulnerabilities & mitigation
Onwukike Chinedu. CISA, CEH, COBIT5 LI, CCNP
 
PDF
Best Practices in Exception Handling
Lemi Orhan Ergin
 
PDF
Unit testing with JUnit
Thomas Zimmermann
 
PDF
Javascript
Rajavel Dhandabani
 
PPTX
Rxjs ppt
Christoffer Noring
 
PDF
Javascript and DOM
Brian Moschel
 
PPT
Exception handling
Tata Consultancy Services
 
PDF
Spring boot introduction
Rasheed Waraich
 
PDF
Demystifying Angular Animations
Gil Fink
 
PDF
Angular Routing Guard
Knoldus Inc.
 
PPTX
Exceptionhandling
Nuha Noor
 
PPTX
Optional in Java 8
Richard Walker
 
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
PDF
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
 
PPT
Exception handling in java
Pratik Soares
 
PPT
Effective Java - Enum and Annotations
Roshan Deniyage
 
PDF
Building Grails applications with PostgreSQL
Command Prompt., Inc
 
PPTX
Exception handling in java
Elizabeth alexander
 
PPT
Advanced Javascript
Adieu
 
PDF
Asynchronous JavaScript Programming
Haim Michael
 
File upload vulnerabilities & mitigation
Onwukike Chinedu. CISA, CEH, COBIT5 LI, CCNP
 
Best Practices in Exception Handling
Lemi Orhan Ergin
 
Unit testing with JUnit
Thomas Zimmermann
 
Javascript
Rajavel Dhandabani
 
Javascript and DOM
Brian Moschel
 
Exception handling
Tata Consultancy Services
 
Spring boot introduction
Rasheed Waraich
 
Demystifying Angular Animations
Gil Fink
 
Angular Routing Guard
Knoldus Inc.
 
Exceptionhandling
Nuha Noor
 
Optional in Java 8
Richard Walker
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
 
Exception handling in java
Pratik Soares
 
Effective Java - Enum and Annotations
Roshan Deniyage
 
Building Grails applications with PostgreSQL
Command Prompt., Inc
 
Exception handling in java
Elizabeth alexander
 
Advanced Javascript
Adieu
 
Asynchronous JavaScript Programming
Haim Michael
 

Similar to Exception handling and logging best practices (20)

PDF
Exception handling & logging in Java - Best Practices (Updated)
Angelin R
 
PDF
10 Typical Enterprise Java Problems
Eberhard Wolff
 
PPTX
exceptionhandlinginjava-140224181412-phpapp02.pptx
ARUNPRANESHS
 
PPTX
Training material exceptions v1
Shinu Suresh
 
PDF
Lecture 9.pdf
SakhilejasonMsibi
 
PDF
10 Typical Problems in Enterprise Java Applications
Eberhard Wolff
 
PDF
Exception Handling.pdf
lsdfjldskjf
 
PPTX
Introduction to java exceptions
Sujit Kumar
 
PPT
Exception handling
Raja Sekhar
 
PDF
Helpful logging with Java
roskakori
 
PPTX
12. Java Exceptions and error handling
Intro C# Book
 
PDF
Perfomatix - Java Coding Standards
Perfomatix Solutions
 
PDF
How i learned to stop worrying and love the logs
Hanokh Aloni
 
PPTX
Exceptions in Java
Vadym Lotar
 
PPT
Exception Handling.ppt
Faisaliqbal203156
 
DOCX
Java Exception handling
Garuda Trainings
 
PPT
Java: Exception
Tareq Hasan
 
PDF
Design byexceptions
Asif Tasleem
 
PPTX
Coding best practices_exception handling
Abid Khan
 
PPT
LoggingBestPractices
Afsaneh Abouie Mehrizi
 
Exception handling & logging in Java - Best Practices (Updated)
Angelin R
 
10 Typical Enterprise Java Problems
Eberhard Wolff
 
exceptionhandlinginjava-140224181412-phpapp02.pptx
ARUNPRANESHS
 
Training material exceptions v1
Shinu Suresh
 
Lecture 9.pdf
SakhilejasonMsibi
 
10 Typical Problems in Enterprise Java Applications
Eberhard Wolff
 
Exception Handling.pdf
lsdfjldskjf
 
Introduction to java exceptions
Sujit Kumar
 
Exception handling
Raja Sekhar
 
Helpful logging with Java
roskakori
 
12. Java Exceptions and error handling
Intro C# Book
 
Perfomatix - Java Coding Standards
Perfomatix Solutions
 
How i learned to stop worrying and love the logs
Hanokh Aloni
 
Exceptions in Java
Vadym Lotar
 
Exception Handling.ppt
Faisaliqbal203156
 
Java Exception handling
Garuda Trainings
 
Java: Exception
Tareq Hasan
 
Design byexceptions
Asif Tasleem
 
Coding best practices_exception handling
Abid Khan
 
LoggingBestPractices
Afsaneh Abouie Mehrizi
 
Ad

More from Angelin R (16)

PPTX
Comparison of Java Web Application Frameworks
Angelin R
 
DOCX
[DOC] Java - Code Analysis using SonarQube
Angelin R
 
PDF
Java Source Code Analysis using SonarQube
Angelin R
 
PDF
The principles of good programming
Angelin R
 
PDF
A Slice of Me
Angelin R
 
PDF
Team Leader - 30 Essential Traits
Angelin R
 
PDF
Action Script
Angelin R
 
PDF
Agile SCRUM Methodology
Angelin R
 
PPT
Tamil Christian Worship Songs
Angelin R
 
PDF
Flex MXML Programming
Angelin R
 
PDF
Introduction to Adobe Flex
Angelin R
 
PDF
Software Development Life Cycle (SDLC)
Angelin R
 
PDF
Restful Web Services
Angelin R
 
PDF
Effective Team Work Model
Angelin R
 
PDF
Team Building Activities
Angelin R
 
PDF
XStream
Angelin R
 
Comparison of Java Web Application Frameworks
Angelin R
 
[DOC] Java - Code Analysis using SonarQube
Angelin R
 
Java Source Code Analysis using SonarQube
Angelin R
 
The principles of good programming
Angelin R
 
A Slice of Me
Angelin R
 
Team Leader - 30 Essential Traits
Angelin R
 
Action Script
Angelin R
 
Agile SCRUM Methodology
Angelin R
 
Tamil Christian Worship Songs
Angelin R
 
Flex MXML Programming
Angelin R
 
Introduction to Adobe Flex
Angelin R
 
Software Development Life Cycle (SDLC)
Angelin R
 
Restful Web Services
Angelin R
 
Effective Team Work Model
Angelin R
 
Team Building Activities
Angelin R
 
XStream
Angelin R
 
Ad

Recently uploaded (20)

DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Digital Circuits, important subject in CS
contactparinay1
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 

Exception handling and logging best practices

  • 2. AGENDA Logging using Log4j “Logging” Best Practices “Exception Handling” Best Practices CodePro Errors and Fixes
  • 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
  • 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. 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”.
  • 6. Logging using Log4j Level Description 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.
  • 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.*; public class LogClass { private static final org.apache.log4j.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!
  • 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.
  • 10. Logging - Best Practices 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.
  • 11. 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 getSkuDescription method”); // The above logging statement is not required, // if getSkuDescription() method logs its method entry String skuDesc = getSkuDescription(skuNumber); LOGGER.debug(“Exited getSkuDescription method”); // The above logging statement is not required, // if getSkuDescription() method logs its method exit } catch (ServiceException se) { LOGGER.error(se.getErrorMessage()); throw se; }
  • 12. Logging - Best Practices Avoid logging at ‘every’ place where a custom exception is thrown and instead log the custom exceptions’ message in its ‘catch’ handler. Example try { if (null == skuNumber || skuNumber.isEmpty()) { LOGGER.error(“Sku number is invalid”); // The above logging statement is not required, // since the catch handler logs the message throw new ServiceException(“Sku number is invalid”); }
  • 13. Logging - Best Practices try { sku = Integer.parseInt(skuNumber); } catch (NumberFormatException nfe) { LOGGER.error(“Sku number is invalid and not a number”); // The above logging statement is not required, // since the catch handler logs the message throw new ServiceException(“Sku number is invalid and not a number”, nfe); } …… } catch (ServiceException se) { LOGGER.error(se.getErrorMessage()); throw se; }
  • 15. Exception Handling - Best Practice #1 Handle Exceptions close to its origin  Does NOT mean “catch and swallow” (i.e. suppress or ignore exceptions) try { // code that is capable of throwing a XyzException } catch ( XyzException e) { // do nothing or simply log and proceed }  It means, “log and throw an exception relevant to that source layer” – DAO layer - DataAccessException – Business layer - ApplicationException (example OUSException)
  • 16. Exception Handling - Best Practice #1 Important Note In applications using Web Services, the Web Service (a.k.a Resource) layer,  should catch ALL exceptions and handle them by creating proper error response and send it back to client.  should NOT allow any exception (checked or unchecked) to be “thrown” to client.  should handle the Business layer exception and all other unchecked exceptions separately.
  • 17. Exception Handling - Best Practice #1 Example try { // code that is capable of throwing an ApplicationException } catch (ApplicationException 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. // form error response using the exception’s // data – error code and/or error message } The catch handler for ‘Exception’ in the Web Service layer is expected to handle all unchecked exceptions thrown from within ‘try’ block
  • 18. 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. try { // code that is capable of throwing a XyzException } catch (XyzException e) { // log the exception specific information // throw exception relevant to that source layer }
  • 19. Exception Handling - Best Practice #2 #1 - When catching an exception and throwing it through an exception relevant to that source layer, make sure to use the construct that passes the original exception’s cause. Otherwise, CodePro will report "No cause specified when creating 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); }
  • 20. Exception Handling - Best Practice #2 #2 - 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) { // LOGGING missed here throw new DataAccessException(“An error occurred when processing the query.”, e); }
  • 21. Exception Handling - Best Practice #2 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 OUSException(e.getMessage(), e); }
  • 22. Exception Handling - Best Practice #3 Do not catch “Exception” Accidentally swallowing RuntimeException try { doSomething(); } catch (Exception e) { LOGGER.error(e.getMessage()); } This code 1. also captures any RuntimeExceptions that might have been thrown by doSomething, 2. ignores unchecked exceptions and 3. prevents them from being propagated.
  • 23. Exception Handling - Best Practice #3 Important Note (about some common RuntimeExceptions) 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.
  • 24. Exception Handling - Best Practice #3 Important Note (about some common RuntimeExceptions) Example try { int sku = Integer.parseInt(skuNumber); } catch (NumberFormatException nfe) { LOGGER.error("SKU number is invalid and not a number"); throw new OUSException("SKU number is invalid and not a number", nfe); } All other unchecked exceptions (RuntimeExceptions) will be caught and handled by the Web Service layer (as explained in Best Practice #1).
  • 26. Fix to common CodePro errors "Invalid exception parameter name" Solution Rename the parameter to “e” Example try { // code that is capable of throwing a DataAccessException } catch (DataAccessException e) { throw new OUSException(e.getMessage(), e); }
  • 27. Fix to common CodePro errors "No cause specified when creating exception" when wrapping an exception into another exception. Solution Use the construct that passes the original exception’s cause Example try { // code that is capable of throwing a SQLException } catch (SQLException e) { LOGGER.error(e.getMessage()); throw new DataAccessException(“An error occurred when searching for the SKU details”, e); }