SlideShare une entreprise Scribd logo
1  sur  22
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

Contenu connexe

Tendances

Unit5 java
Unit5 javaUnit5 java
Unit5 java
mrecedu
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
Tricode (part of Dept)
 

Tendances (19)

Error handling and debugging in vb
Error handling and debugging in vbError handling and debugging in vb
Error handling and debugging in vb
 
.Net Debugging Techniques
.Net Debugging Techniques.Net Debugging Techniques
.Net Debugging Techniques
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Lecture 20-21
Lecture 20-21Lecture 20-21
Lecture 20-21
 
Exception handling
Exception handlingException handling
Exception handling
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
 
How to handle exceptions in Java Technology
How to handle exceptions in Java Technology How to handle exceptions in Java Technology
How to handle exceptions in Java Technology
 
Introduction of exception in vb.net
Introduction of exception in vb.netIntroduction of exception in vb.net
Introduction of exception in vb.net
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done Right
 
Unit5 java
Unit5 javaUnit5 java
Unit5 java
 
Implementing Blackbox Testing
Implementing Blackbox TestingImplementing Blackbox Testing
Implementing Blackbox Testing
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 
Realtime selenium interview questions
Realtime selenium interview questionsRealtime selenium interview questions
Realtime selenium interview questions
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Debugging in .Net
Debugging in .NetDebugging in .Net
Debugging in .Net
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
PVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniquePVS-Studio and static code analysis technique
PVS-Studio and static code analysis technique
 

En vedette (7)

2015 semicon taiwan mb v2
2015 semicon taiwan mb v22015 semicon taiwan mb v2
2015 semicon taiwan mb v2
 
Procurement best practices
Procurement best practicesProcurement best practices
Procurement best practices
 
Global Chief Procurement Officer Survey 2010 Final Web Edition
Global Chief Procurement Officer Survey 2010  Final Web EditionGlobal Chief Procurement Officer Survey 2010  Final Web Edition
Global Chief Procurement Officer Survey 2010 Final Web Edition
 
Basics Of Procurement Process
Basics Of Procurement ProcessBasics Of Procurement Process
Basics Of Procurement Process
 
The role of procurement
The role of procurementThe role of procurement
The role of procurement
 
Procurement: Strategies | Best Practices
Procurement: Strategies | Best PracticesProcurement: Strategies | Best Practices
Procurement: Strategies | Best Practices
 
Top 10 Procurement KPI\'s
Top 10 Procurement KPI\'sTop 10 Procurement KPI\'s
Top 10 Procurement KPI\'s
 

Similaire à Training material exceptions v1

Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptions
Sujit Kumar
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Design byexceptions
Design byexceptionsDesign byexceptions
Design byexceptions
Asif Tasleem
 
Errors and exception
Errors and exceptionErrors and exception
Errors and exception
Rishav Upreti
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
Alpesh Oza
 

Similaire à Training material exceptions v1 (20)

Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptions
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
Exception
ExceptionException
Exception
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Design byexceptions
Design byexceptionsDesign byexceptions
Design byexceptions
 
Errors and exception
Errors and exceptionErrors and exception
Errors and exception
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Exception handling
Exception handlingException handling
Exception handling
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
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
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 

Plus de Shinu Suresh (6)

Hybris 6.0.0 to 6.3.0 comparision
Hybris 6.0.0 to 6.3.0 comparisionHybris 6.0.0 to 6.3.0 comparision
Hybris 6.0.0 to 6.3.0 comparision
 
Git
GitGit
Git
 
Continuous Integrations & Deployments
Continuous Integrations & DeploymentsContinuous Integrations & Deployments
Continuous Integrations & Deployments
 
GitFlow, SourceTree and GitLab
GitFlow, SourceTree and GitLabGitFlow, SourceTree and GitLab
GitFlow, SourceTree and GitLab
 
Websphere Commerce SEO
Websphere Commerce SEOWebsphere Commerce SEO
Websphere Commerce SEO
 
Training material sonar v1
Training material   sonar v1Training material   sonar v1
Training material sonar v1
 

Dernier

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.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

Notes de l'éditeur

  1. 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