Aspectj Cookbook

Recipe 5.1. Capturing When an Exception Is Caught

Problem

You want to capture when a particular type of exception is caught.

Solution

Use the handler(TypePattern) pointcut. The syntax of the handler(TypePattern) pointcut is:

pointcut <pointcut name>(<any values to be picked up>) : handler(<class>);

Discussion

The handler(TypePattern) pointcut has five key characteristics:

  1. The handler(TypePattern) pointcut picks up join points within the scope of where a exception is caught.

  2. The handler(TypePattern) pointcut's advice will only be applied where the type pattern specifies Throwable or a subclass of Throwable.

  3. The TypePattern declares that whenever the matching type of exception, or a subclass of that exception, is caught, then the corresponding advice is to be applied.

  4. Only the before( ) form of advice is supported on handler(TypePattern) pointcuts. This means that you cannot override the normal behavior of a catch block using something like around( ) advice.

  5. The TypePattern can include wildcard characters to select a range of join points on different classes.

Table 5-1 shows some examples of the wildcard options available when using a TypePattern to a pointcut declaration.

Table 5-1. Examples of using wildcards within a TypePattern

TypePattern with wildcards

Description

mypackage..*

Captures join points class within the mypackage package and subpackages.

MyClass+

Captures join points within the MyClass class and any subclasses.

Example 5-1 shows the handler(TypePattern) pointcut to capture a MyException exception being caught.

Example 5-1. Using the handler(TypePattern) pointcut to capture join points when a specific type of exception is caught

public aspect HandlerRecipe { /* Specifies calling advice when any exception object is caught that matches the following rules for its type pattern: Type: MyException */ pointcut myExceptionHandlerPointcut( ) : handler(MyException); // Advice declaration before( ) : myExceptionHandlerPointcut( ) { System.out.println( "-------------- Aspect Advice Logic ---------------"); System.out.println( "In the advice picked by " + "myExceptionHandlerPointcut( )"); System.out.println( "Signature: " + thisJoinPoint.getStaticPart( ).getSignature( )); System.out.println( "Source Line: " + thisJoinPoint.getStaticPart( ).getSourceLocation( )); System.out.println( "--------------------------------------------------"); } }

The handler(TypePattern) pointcut captures join points where an exception is caught, not where it is raised.

Figure 5-1 shows how the handler(TypePattern) pointcut is applied to a simple class hierarchy.

Figure 5-1. How the handler(TypePattern) pointcut is applied

See Also

Chapter 13 describes the different types of advice available in AspectJ.

Категории