Top Banner
Training Material Exception Handling By Shinu Suresh
22

Training material exceptions v1

Sep 05, 2014

Download

Technology

Shinu Suresh

Presentation on Java and Websphere commerce exception handling
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Training material   exceptions v1

Training MaterialException Handling

By Shinu Suresh

Page 2: Training material   exceptions v1

Agenda

• Exceptions• Exceptions by Nature• Types of Exceptions• Handling Exceptions• Handling Exceptions in Websphere Commerce

Page 3: Training material   exceptions v1

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

Page 4: Training material   exceptions v1

Nature of Exceptions

• Exceptions due to programming errorsExceptions 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 errorsClient code attempts something not allowed by the API, and thereby violates its contract.

• Exceptions due to resource failuresExceptions 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)

Page 5: Training material   exceptions v1

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

Page 6: Training material   exceptions v1

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.

Page 7: Training material   exceptions v1

Object Throwable

Error

LinkageError

VirtualMachineError

StackOverrflowError

OutOfMemoryError

Exception

IOException

FileNotFoundException

SocketException

UnKnownHostExceptionNoSuchMethodException

RuntimeException

NullPointerException

ClassCastException

IndexOutOfBoundsException

Checked

UnChecked

Page 8: Training material   exceptions v1

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.

Page 9: Training material   exceptions v1

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.

Page 10: Training material   exceptions v1

Handling Exceptions

• Declaring ExceptionMethod should declare the exception it throws in its signature

UnChecked exceptions need not be thrown

• Throwing an ExceptionWhen 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 ... }

Page 11: Training material   exceptions v1

Handling Exceptions Cont.

• Catching an ExceptionWhen 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

} ... }

Page 12: Training material   exceptions v1

Handling Exceptions in Websphere Commerce• Well defined and simple to use in customized code• Supports multicultural stores• Tightly integrated with Logging systemTwo Types of Exceptions primarily

Exception

ECApplicationException ECSystemException

Page 13: Training material   exceptions v1

Exception Flow

Solution Controller invokes Controller

Command

Command throws exception

(ECApplicationException or ECSystemException)

Struts determines error global forward and

invoke specified error view

Page 14: Training material   exceptions v1

• ECApplicationExceptionThis 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.

• ECSystemExceptionThis exception is thrown if a runtime exception or a WebSphere Commerce configuration error is detected. Examples of this type of exception include

1. Create exceptions2. Remote Exception3. 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.

Page 15: Training material   exceptions v1

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

Page 16: Training material   exceptions v1

Exampletry{

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

Page 17: Training material   exceptions v1

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

Page 18: Training material   exceptions v1

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

Page 19: Training material   exceptions v1

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.

Page 20: Training material   exceptions v1

Payment Exceptions

Exception BaseException

EDPException

InvalidDataException

CommunicationException

ConfigurationException

PluginException

InvalidDataException

CommunicationException

InternalErrorException

TimeoutException

FinancialException

ApprovalExpiredException

InvalidPaymentInstructionExcepiton

PaymentInstructionBlockedException

Page 21: Training material   exceptions v1

Payment Exceptions cont

• EDPExceptionThe root exception of the Payment rules engine

• PluginExceptionThe 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 referencehttp://pic.dhe.ibm.com/infocenter/wchelp/v7r0m0/topic/com.ibm.commerce.payments.events.doc/refs/rppppcspec.htm?resultof=%22%70%61%79%6d%65%6e%74%22%20%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

Page 22: Training material   exceptions v1

Thank You