SlideShare a Scribd company logo
Training Material
Exception Handling
By Shinu Suresh
Agenda
• Exceptions
• Exceptions by Nature
• Types of Exceptions
• Handling Exceptions
• Handling Exceptions in Websphere Commerce
Exceptions
“An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program’s instructions”
• Exceptional conditions are not necessarily rare
Nature of Exceptions
• Exceptions due to programming errors
Exceptions are generated due to programming errors
(e.g., NullPointerException and IllegalArgumentException). The client code usually
cannot do anything about programming errors.
• Exceptions due to client code errors
Client code attempts something not allowed by the API, and thereby violates its
contract.
• Exceptions due to resource failures
Exceptions that get generated when resources fail. For example: network connection
fails.
• The parameters given to the method are not well defined (i.e. are wrong /
null where they must not be)
Cont..
• The "constellation" of the parameter values are not expected in the given
way by the method (because if parameter "a" has a certain value, "b" must
not be of another certain value)
• The caller of the method simply calls it in an improper way (i.e. the
environmental conditions are not correct, needed resources are not
allocated yet etc.)
• The method allocates external resources (i.e. open connections, file
handles etc.) and does not free them (thus leading to an invalid internal
state of the program, the operating system or other components like
databases)
• The method relies on external resources (i.e. file system, database etc.)
which are not available at the moment they are needed
Types of Exception
• Checked exceptions: Exceptions that inherit from the Exception class
are checked exceptions. Client code has to handle the checked
exceptions thrown by the API, either in a catch clause or by
forwarding it outward with the throws clause.
• Unchecked exceptions: RuntimeException also extends from
Exception. However, all of the exceptions that inherit from
RuntimeException get special treatment. There is no requirement for
the client code to deal with them, and hence they are called
unchecked exceptions.
Object Throwable
Error
LinkageError
VirtualMachineError
StackOverrflowError
OutOfMemoryError
Exception
IOException
FileNotFoundException
SocketException
UnKnownHostException
NoSuchMethodException
RuntimeException
NullPointerException
ClassCastException
IndexOutOfBoundsException
Checked
UnChecked
Java.lang.Error
• Errors (members of the Error family) are usually thrown for more serious
problems, such as OutOfMemoryError, that may not be so easy to handle.
In general, code you write should throw only exceptions, not errors. Errors
are usually thrown by the methods of the Java API, or by the Java virtual
machine itself.
• Errors usually signal abnormal conditions that you wouldn't want a
program to handle. Problems with linking, such as NoClassDefFoundError,
or memory, such as StackOverflowError, could happen just about anywhere
in a program. In the rare cases in which they happen, it is usually
reasonable that the thread terminate.
• Java Language Specification advises against throwing errors. It is intended
that errors be thrown only by the Java runtime.
Checked vs Unchecked
Client reaction when exception happens Exception Type
Client code cannot do anything Make it an UnChecked Exception
Client code will take some useful recovery actions
based on information in exception
Make it Checked Exception
If you are throwing an exception to indicate an
improper use of your class, you are signalling a
software bug
Descend from RuntimeException which will make it
UnChecked
If you are throwing an exception to indicate not a
software bug but an abnormal condition that client
programmers should deal with every time they use
your method
Make it Checked Exception
One design approach often discussed in the context of object-oriented programming is the Design by Contract
approach. This approach to software design says that a method represents a contract between the client (the
caller of the method) and the class that declares the method. The contract includes preconditions that the
client must fulfil and postconditions that the method itself must fulfil.
Handling Exceptions
• Declaring Exception
Method should declare the exception it throws in its signature
UnChecked exceptions need not be thrown
• Throwing an Exception
When program encounters an abnormal operation, the method containing the erroneous statement
create an appropriate Exception object and throw it
public void methodD() throws XxxException, YyyException { // method's signature // method body throw XxxException
and YyyException }
public void methodD() throws XxxException, YyyException { // method's signature
// method's body ... ...
// XxxException occurs
if ( ... )
throw new XxxException(...); // construct an XxxException object and throw to JRE
... // YyyException occurs
if ( ... )
throw new YyyException(...); // construct an YyyException object and throw to JRE ...
}
Handling Exceptions Cont.
• Catching an Exception
When a method throws an exception, the Java runtime searches backward through the call stack for a
matching exception handler. Each exception handler can handle one particular class of exception. If no
exception handler is found in the call stack, the program terminates.
public void methodC() { // no exception declared
...
try {
... // uses methodD() which declares XxxException & YyyException
methodD();
...
} catch (XxxException ex) {
// Exception handler for XxxException
...
} catch (YyyException ex} { // Exception handler for YyyException
...
} finally { // optional
// These codes always run, used for cleaning up
}
...
}
Handling Exceptions in Websphere
Commerce
• Well defined and simple to use in customized code
• Supports multicultural stores
• Tightly integrated with Logging system
Two Types of Exceptions primarily
Exception
ECApplicationException ECSystemException
Exception Flow
Solution Controller
invokes Controller
Command
Command throws
exception
(ECApplicationException
or ECSystemException)
Struts determines error
global forward and
invoke specified error
view
• ECApplicationException
This exception is thrown if the error is related to user input and will always fail. For
example, when a user enters an invalid parameter, an ECApplicationException is
thrown. When this exception is thrown, the solution controller does not retry the
command, even if it is specified as a retriable command.
• ECSystemException
This exception is thrown if a runtime exception or a WebSphere Commerce
configuration error is detected. Examples of this type of exception include
1. Create exceptions
2. Remote Exception
3. EJB Exceptions
When this type of exception is thrown, the solution controller retries the command if
the command is retriable and the exception was caused by either a database deadlock
or database rollback.
Points to remember
• Exceptions should generally be allowed to propagate up the stack
ultimately resulting in a roll-back and error response. This might mean
catching and re-throwing exceptions. If this is the case, exceptions should
always include the original exception so that the root cause is known. An
example would be a retry in the case of a network failure etc.
• If the operation can be retried then it should be.
• Exceptions should not be used to implement business logic (there is a
performance overhead with throwing an exception)
• Exceptions should never just be caught and ignored
• Exception handling framework will be developed for the project wherein all
Exceptions will be either XApplicationException or XSystemException
Example
try{
//---------------------
//<Business logic>
//---------------------
}catch(ECApplicationException e){
throw new XApplicationException(exp.getECMessage(),this.CLASS_NAME,METHOD_NAME, LoggerIdentifier.COMPONENT_CATALOG);
} catch(ECSystemException e){
throw new XSystemException(exp.getECMessage(),this.CLASS_NAME,METHOD_NAME, LoggerIdentifier.COMPONENT_CATALOG);
}
1. Produces a stack trace for any exception caught.
2. Parameters are logged at the time of the exception.
3. ECExceptions and its subclasses are logged only once.
Exception Logging
• Uses WCS Logging framework
• Entering and exiting method logging must be provided
• Use entering () and exiting () methods on the Logger and not log
(Level.INFO, "Entering method xxx...");
• Different log levels are there for a reason. So be careful what you will log
using INFO level. Probably no one (except you) is interested in list of
parameters and values going to your direct SQL query or details about a
person. This should be really using FINE or lower.
• Log a meaningful message. Parameter=value type of message doesn't
count as meaningful
• Logging liberally with FINE which will help in debugging issues in LIVE
JSP And Error handling
• Use StoreErrorDataBean to display store specific error messages in JSP
page
The databean provides getter methods to
• Retrieve the store error key, <ECMessageKey>.<Error Code>
• Retrieve the error message parameters, that is, the substitution
parameters used in the error messages
StoreDataBean rely on existence of store error message properties file.
Eg:- storeErrorMessages_ locale.properties
Using StoreDataBean in JSP
<wcbase:useBean id="storeError“ classname="com.ibm.commerce.common.beans.StoreErrorDataBean“ scope="page">
<c:set target="${storeError}" property="resourceBundleName“ value="${sdb.jspStoreDir}/storeErrorMessages" />
</wcbase:useBean>
<c:if test="${!empty storeError.key}">
<c:set var="errorMessage" value="${storeError.message}" />
</c:if>
//storeErrorMessages_ locale.properties
_ERR_CMD_INVALID_PARAM.2020 = Type an e-mail address in the E-mail address field.
Payment Exceptions
Exception BaseException
EDPException
InvalidDataException
CommunicationException
ConfigurationException
PluginException
InvalidDataException
CommunicationException
InternalErrorException
TimeoutException
FinancialException
ApprovalExpiredException
InvalidPaymentInstructionExcepiton
PaymentInstructionBlockedException
Payment Exceptions cont
• EDPException
The root exception of the Payment rules engine
• PluginException
The root exception of the payments plug-in. Throw this exception in case of
exceptional scenarios or if you don’t find any suitable exceptions in the already existing
ones
For more reference
http://pic.dhe.ibm.com/infocenter/wchelp/v7r0m0/topic/com.ibm.commerce.paymen
ts.events.doc/refs/rppppcspec.htm?resultof=%22%70%61%79%6d%65%6e%74%22%2
0%22%65%72%72%6f%72%22%20%22%68%61%6e%64%6c%69%6e%67%22%20%22
%68%61%6e%64%6c%22%20
Thank You

More Related Content

PPTX
Exception handling in ASP .NET
PPT
Exception Handling Java
PPT
12 exception handling
PPT
Week7 exception handling
PPT
Itp 120 Chapt 18 2009 Exceptions & Assertions
PPT
C# Exceptions Handling
PPTX
Java Exceptions and Exception Handling
PDF
Best Practices in Exception Handling
Exception handling in ASP .NET
Exception Handling Java
12 exception handling
Week7 exception handling
Itp 120 Chapt 18 2009 Exceptions & Assertions
C# Exceptions Handling
Java Exceptions and Exception Handling
Best Practices in Exception Handling

What's hot (19)

PPTX
Error handling and debugging in vb
PPT
.Net Debugging Techniques
PPTX
Exception Handling
PPTX
Lecture 20-21
PPT
Exception handling
PPTX
Unit Tests And Automated Testing
PDF
Unit Testing 101
PPSX
How to handle exceptions in Java Technology
PPT
Introduction of exception in vb.net
PDF
Unit Testing
PDF
Unit Testing Done Right
DOCX
Unit5 java
PDF
Implementing Blackbox Testing
ODP
Embrace Unit Testing
DOCX
Realtime selenium interview questions
PPT
Unit testing php-unit - phing - selenium_v2
PPTX
Debugging in .Net
PPS
Why Unit Testingl
PPTX
PVS-Studio and static code analysis technique
Error handling and debugging in vb
.Net Debugging Techniques
Exception Handling
Lecture 20-21
Exception handling
Unit Tests And Automated Testing
Unit Testing 101
How to handle exceptions in Java Technology
Introduction of exception in vb.net
Unit Testing
Unit Testing Done Right
Unit5 java
Implementing Blackbox Testing
Embrace Unit Testing
Realtime selenium interview questions
Unit testing php-unit - phing - selenium_v2
Debugging in .Net
Why Unit Testingl
PVS-Studio and static code analysis technique
Ad

Viewers also liked (7)

PDF
2015 semicon taiwan mb v2
PPT
Procurement best practices
PDF
Global Chief Procurement Officer Survey 2010 Final Web Edition
PPT
Basics Of Procurement Process
PPT
The role of procurement
PDF
Procurement: Strategies | Best Practices - May 2011
PPT
Top 10 Procurement KPI\'s
2015 semicon taiwan mb v2
Procurement best practices
Global Chief Procurement Officer Survey 2010 Final Web Edition
Basics Of Procurement Process
The role of procurement
Procurement: Strategies | Best Practices - May 2011
Top 10 Procurement KPI\'s
Ad

Similar to Training material exceptions v1 (20)

PPT
Exception handling
PPT
Exception handling
PPTX
Exceptions in Java
PPTX
Introduction to java exceptions
PPTX
Exceptions overview
PPTX
Exception Handling In Java Presentation. 2024
PPTX
Java-Exception Handling Presentation. 2024
PPTX
PPTX
JAVA Presenttation topics Programs.pptx
PPT
Exception
PPT
Exception Handling Exception Handling Exception Handling
PDF
Design byexceptions
PPT
Errors and exception
PPT
Week7 exception handling
PPT
Week7 exception handling
PPTX
Pi j4.2 software-reliability
PPT
Exception handling
PPTX
L14 exception handling
PDF
Class notes(week 8) on exception handling
PPT
A36519192_21789_4_2018_Exception Handling.ppt
Exception handling
Exception handling
Exceptions in Java
Introduction to java exceptions
Exceptions overview
Exception Handling In Java Presentation. 2024
Java-Exception Handling Presentation. 2024
JAVA Presenttation topics Programs.pptx
Exception
Exception Handling Exception Handling Exception Handling
Design byexceptions
Errors and exception
Week7 exception handling
Week7 exception handling
Pi j4.2 software-reliability
Exception handling
L14 exception handling
Class notes(week 8) on exception handling
A36519192_21789_4_2018_Exception Handling.ppt

More from Shinu Suresh (6)

PPTX
Hybris 6.0.0 to 6.3.0 comparision
PPTX
PPTX
Continuous Integrations & Deployments
PPTX
GitFlow, SourceTree and GitLab
PPTX
Websphere Commerce SEO
PPTX
Training material sonar v1
Hybris 6.0.0 to 6.3.0 comparision
Continuous Integrations & Deployments
GitFlow, SourceTree and GitLab
Websphere Commerce SEO
Training material sonar v1

Recently uploaded (20)

PPTX
TLE Review Electricity (Electricity).pptx
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
A comparative study of natural language inference in Swahili using monolingua...
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Approach and Philosophy of On baking technology
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPT
Teaching material agriculture food technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
A Presentation on Artificial Intelligence
PDF
Mushroom cultivation and it's methods.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
TLE Review Electricity (Electricity).pptx
Assigned Numbers - 2025 - Bluetooth® Document
A comparative study of natural language inference in Swahili using monolingua...
Programs and apps: productivity, graphics, security and other tools
Approach and Philosophy of On baking technology
SOPHOS-XG Firewall Administrator PPT.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Teaching material agriculture food technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
NewMind AI Weekly Chronicles - August'25-Week II
Mobile App Security Testing_ A Comprehensive Guide.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
A Presentation on Artificial Intelligence
Mushroom cultivation and it's methods.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
A comparative analysis of optical character recognition models for extracting...
Group 1 Presentation -Planning and Decision Making .pptx

Training material exceptions v1

  • 2. Agenda • Exceptions • Exceptions by Nature • Types of Exceptions • Handling Exceptions • Handling Exceptions in Websphere Commerce
  • 3. Exceptions “An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions” • Exceptional conditions are not necessarily rare
  • 4. Nature of Exceptions • Exceptions due to programming errors Exceptions are generated due to programming errors (e.g., NullPointerException and IllegalArgumentException). The client code usually cannot do anything about programming errors. • Exceptions due to client code errors Client code attempts something not allowed by the API, and thereby violates its contract. • Exceptions due to resource failures Exceptions that get generated when resources fail. For example: network connection fails. • The parameters given to the method are not well defined (i.e. are wrong / null where they must not be)
  • 5. Cont.. • The "constellation" of the parameter values are not expected in the given way by the method (because if parameter "a" has a certain value, "b" must not be of another certain value) • The caller of the method simply calls it in an improper way (i.e. the environmental conditions are not correct, needed resources are not allocated yet etc.) • The method allocates external resources (i.e. open connections, file handles etc.) and does not free them (thus leading to an invalid internal state of the program, the operating system or other components like databases) • The method relies on external resources (i.e. file system, database etc.) which are not available at the moment they are needed
  • 6. Types of Exception • Checked exceptions: Exceptions that inherit from the Exception class are checked exceptions. Client code has to handle the checked exceptions thrown by the API, either in a catch clause or by forwarding it outward with the throws clause. • Unchecked exceptions: RuntimeException also extends from Exception. However, all of the exceptions that inherit from RuntimeException get special treatment. There is no requirement for the client code to deal with them, and hence they are called unchecked exceptions.
  • 8. Java.lang.Error • Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError, that may not be so easy to handle. In general, code you write should throw only exceptions, not errors. Errors are usually thrown by the methods of the Java API, or by the Java virtual machine itself. • Errors usually signal abnormal conditions that you wouldn't want a program to handle. Problems with linking, such as NoClassDefFoundError, or memory, such as StackOverflowError, could happen just about anywhere in a program. In the rare cases in which they happen, it is usually reasonable that the thread terminate. • Java Language Specification advises against throwing errors. It is intended that errors be thrown only by the Java runtime.
  • 9. Checked vs Unchecked Client reaction when exception happens Exception Type Client code cannot do anything Make it an UnChecked Exception Client code will take some useful recovery actions based on information in exception Make it Checked Exception If you are throwing an exception to indicate an improper use of your class, you are signalling a software bug Descend from RuntimeException which will make it UnChecked If you are throwing an exception to indicate not a software bug but an abnormal condition that client programmers should deal with every time they use your method Make it Checked Exception One design approach often discussed in the context of object-oriented programming is the Design by Contract approach. This approach to software design says that a method represents a contract between the client (the caller of the method) and the class that declares the method. The contract includes preconditions that the client must fulfil and postconditions that the method itself must fulfil.
  • 10. Handling Exceptions • Declaring Exception Method should declare the exception it throws in its signature UnChecked exceptions need not be thrown • Throwing an Exception When program encounters an abnormal operation, the method containing the erroneous statement create an appropriate Exception object and throw it public void methodD() throws XxxException, YyyException { // method's signature // method body throw XxxException and YyyException } public void methodD() throws XxxException, YyyException { // method's signature // method's body ... ... // XxxException occurs if ( ... ) throw new XxxException(...); // construct an XxxException object and throw to JRE ... // YyyException occurs if ( ... ) throw new YyyException(...); // construct an YyyException object and throw to JRE ... }
  • 11. Handling Exceptions Cont. • Catching an Exception When a method throws an exception, the Java runtime searches backward through the call stack for a matching exception handler. Each exception handler can handle one particular class of exception. If no exception handler is found in the call stack, the program terminates. public void methodC() { // no exception declared ... try { ... // uses methodD() which declares XxxException & YyyException methodD(); ... } catch (XxxException ex) { // Exception handler for XxxException ... } catch (YyyException ex} { // Exception handler for YyyException ... } finally { // optional // These codes always run, used for cleaning up } ... }
  • 12. Handling Exceptions in Websphere Commerce • Well defined and simple to use in customized code • Supports multicultural stores • Tightly integrated with Logging system Two Types of Exceptions primarily Exception ECApplicationException ECSystemException
  • 13. Exception Flow Solution Controller invokes Controller Command Command throws exception (ECApplicationException or ECSystemException) Struts determines error global forward and invoke specified error view
  • 14. • ECApplicationException This exception is thrown if the error is related to user input and will always fail. For example, when a user enters an invalid parameter, an ECApplicationException is thrown. When this exception is thrown, the solution controller does not retry the command, even if it is specified as a retriable command. • ECSystemException This exception is thrown if a runtime exception or a WebSphere Commerce configuration error is detected. Examples of this type of exception include 1. Create exceptions 2. Remote Exception 3. EJB Exceptions When this type of exception is thrown, the solution controller retries the command if the command is retriable and the exception was caused by either a database deadlock or database rollback.
  • 15. Points to remember • Exceptions should generally be allowed to propagate up the stack ultimately resulting in a roll-back and error response. This might mean catching and re-throwing exceptions. If this is the case, exceptions should always include the original exception so that the root cause is known. An example would be a retry in the case of a network failure etc. • If the operation can be retried then it should be. • Exceptions should not be used to implement business logic (there is a performance overhead with throwing an exception) • Exceptions should never just be caught and ignored • Exception handling framework will be developed for the project wherein all Exceptions will be either XApplicationException or XSystemException
  • 16. Example try{ //--------------------- //<Business logic> //--------------------- }catch(ECApplicationException e){ throw new XApplicationException(exp.getECMessage(),this.CLASS_NAME,METHOD_NAME, LoggerIdentifier.COMPONENT_CATALOG); } catch(ECSystemException e){ throw new XSystemException(exp.getECMessage(),this.CLASS_NAME,METHOD_NAME, LoggerIdentifier.COMPONENT_CATALOG); } 1. Produces a stack trace for any exception caught. 2. Parameters are logged at the time of the exception. 3. ECExceptions and its subclasses are logged only once.
  • 17. Exception Logging • Uses WCS Logging framework • Entering and exiting method logging must be provided • Use entering () and exiting () methods on the Logger and not log (Level.INFO, "Entering method xxx..."); • Different log levels are there for a reason. So be careful what you will log using INFO level. Probably no one (except you) is interested in list of parameters and values going to your direct SQL query or details about a person. This should be really using FINE or lower. • Log a meaningful message. Parameter=value type of message doesn't count as meaningful • Logging liberally with FINE which will help in debugging issues in LIVE
  • 18. JSP And Error handling • Use StoreErrorDataBean to display store specific error messages in JSP page The databean provides getter methods to • Retrieve the store error key, <ECMessageKey>.<Error Code> • Retrieve the error message parameters, that is, the substitution parameters used in the error messages StoreDataBean rely on existence of store error message properties file. Eg:- storeErrorMessages_ locale.properties
  • 19. Using StoreDataBean in JSP <wcbase:useBean id="storeError“ classname="com.ibm.commerce.common.beans.StoreErrorDataBean“ scope="page"> <c:set target="${storeError}" property="resourceBundleName“ value="${sdb.jspStoreDir}/storeErrorMessages" /> </wcbase:useBean> <c:if test="${!empty storeError.key}"> <c:set var="errorMessage" value="${storeError.message}" /> </c:if> //storeErrorMessages_ locale.properties _ERR_CMD_INVALID_PARAM.2020 = Type an e-mail address in the E-mail address field.
  • 21. Payment Exceptions cont • EDPException The root exception of the Payment rules engine • PluginException The root exception of the payments plug-in. Throw this exception in case of exceptional scenarios or if you don’t find any suitable exceptions in the already existing ones For more reference http://pic.dhe.ibm.com/infocenter/wchelp/v7r0m0/topic/com.ibm.commerce.paymen ts.events.doc/refs/rppppcspec.htm?resultof=%22%70%61%79%6d%65%6e%74%22%2 0%22%65%72%72%6f%72%22%20%22%68%61%6e%64%6c%69%6e%67%22%20%22 %68%61%6e%64%6c%22%20

Editor's Notes

  • #21: For each kind of PluginException, there is a corresponding type of EDPException. For example, com.ibm.commerce.payments.plugin.InvalidDataException is a PluginException, and com.ibm.commerce.edp.api.InvalidDataException is its corresponding EDPException. InvalidDataException – If Shopper submits invalid payment