Recipe16.5.Softening Exceptions


Recipe 16.5. Softening Exceptions

Problem

You want to specify a set of exceptions that should be softenedi.e., converted to uncaught exceptionswhen raised on the join points selected by a specific pointcut.

Solution

Use the declare soft statement.

Discussion

Example 16-6 shows softening the ExceptionA exception that is raised on the void foo( ) method so the users of that method do not have to worry about handling that exception.

Example 16-6. Softening exceptions on a method call
public aspect SoftenExceptionRecipe  {    pointcut callPointCut( ) : call(void MyClass.foo( ));    declare soft : ExceptionA : callPointCut( ); }

Java supports two types of exception; checked and unchecked (runtime) exceptions. Checked exceptions extend from java.lang.Exception and get their name because of the following reason: if they are declared as being raised by a particular method, then calling methods must handle those exceptions explicitly otherwise the compiler will complain. Runtime exceptions extended from java.lang.RuntimeException or java.lang.Error, can be raised at any point during an applications lifetime, but do not need to be explicitly caught.

Softening exceptions involves wrapping a checked exception raised on a particular join point in an instance of the org.aspectj.lang.SoftException runtime exception class. Prior to applying softening of the ExceptionA exception, it would have to be caught or re-thrown, as shown in Example 16-7.

Example 16-7. The exception handling required if the exception is not softened
... try {    myObject.foo( ); } catch (ExceptionA ea) {    ea.printStackTrace( ); } ...

By converting the checked exception to a runtime exception, the class can be used without the need for exception handling, as shown in Example 16-8.

Example 16-8. When the exception is softened, then no exception handling is necessary
... myObject.foo( ); ...

Declaring exceptions should be softened in this manner so the surrounding methods do not have to worry about catching those exceptions. Though the exception has been softened, it can still be raised and is more likely not to be caught until it reaches the surrounding system producing an output similar to that shown in Example 16-9.

Example 16-9. Output from a softened exception being thrown and not caught in this recipe's example application
Exception in thread "main" org.aspectj.lang.SoftException         at MyClass.main(MyClass.java:14) Caused by: ExceptionA         at MyClass.foo(MyClass.java:7)         ... 1 more

See Also

The AspectJ language API, including the SoftException class, is covered in more detail in the Appendix; using the handler(TypePattern) pointcut to capture join points when types of exceptions are caught is covered in Recipe 5.1.



AspectJ Cookbook
Aspectj Cookbook
ISBN: 0596006543
EAN: 2147483647
Year: 2006
Pages: 203
Authors: Russ Miles

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net