Training material exceptions v1


Published on

Presentation on Java and Websphere commerce exception handling

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • For each kind of PluginException, there is a corresponding type of EDPException. For example, is a PluginException, and is its corresponding EDPException.InvalidDataException – If Shopper submits invalid payment
  • Training material exceptions v1

    1. 1. Training Material Exception Handling By Shinu Suresh
    2. 2. Agenda • Exceptions • Exceptions by Nature • Types of Exceptions • Handling Exceptions • Handling Exceptions in Websphere Commerce
    3. 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. 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. 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. 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.
    7. 7. LinkageError VirtualMachineError Error StackOverrflowError OutOfMemoryError Object Throwable FileNotFoundException IOException SocketException NoSuchMethodException UnKnownHostException Exception NullPointerException Checked RuntimeException ClassCastException UnChecked IndexOutOfBoundsException
    8. 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. 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. 10. Handling Exceptions • Declaring Exception Method should declare the exception it throws in its signature public void methodD() throws XxxException, YyyException { // method's signature // method body throw XxxException and YyyException } 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'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. 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. 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. 13. Exception Flow Solution Controller invokes Controller Command Struts determines error global forward and invoke specified error view Command throws exception (ECApplicationException or ECSystemException)
    14. 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. 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. 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. 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. 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_
    19. 19. Using StoreDataBean in JSP //storeErrorMessages_ _ERR_CMD_INVALID_PARAM.2020 = Type an e-mail address in the E-mail address field. <wcbase:useBean id="storeError“ classname="“ 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>
    20. 20. Payment Exceptions InvalidDataException EDPException CommunicationException ConfigurationException Exception BaseException InvalidDataException CommunicationException PluginException InternalErrorException TimeoutException ApprovalExpiredException FinancialException InvalidPaymentInstructionExcepiton PaymentInstructionBlockedException
    21. 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 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
    22. 22. Thank You