Recipe 13.7. Executing Advice Only After an Exception Has Been Raised in a Join PointProblemYou want advice to execute after a specific join point only if that join point raised an exception. SolutionUse the after( ) tHRowing or after() throwing(<ExceptionType> <Identifier>) types of advice DiscussionExample 13-8 shows how to specify that advice should be executed if the call to the void MyClass.foo(int) method returns with an exception. Example 13-8. Executing advice after a method call if that call raises an exceptionpublic aspect AfterThrowingAdviceRecipe { /* Specifies calling advice whenever a method matching the following rules gets called: Class Name: MyClass Method Name: foo Method Return Type: void Method Parameters: an int followed by a String */ pointcut callPointCut( ) : call(void MyClass.foo(int)); // Advice declaration after( ) throwing : callPointCut( ) && !within(AfterThrowingAdviceRecipe +) { System.out.println( "------------------- Aspect Advice Logic --------------------"); System.out.println( "Source Location: " + thisJoinPoint.getStaticPart( ).getSourceLocation( )); System.out.println( "------------------------------------------------------------"); } } The after( ) throwing advice type completes the picture for applying advice to be executed after a join point returns. In this case, the advice should be executed when an exception has occurred. This gives the developer the capability to handle exceptional circumstances after a join point has been executed. See AlsoThe call(Signature) pointcut is described in Recipe 4.1; the handler(TypePattern) pointcut is shown in more detail in Recipe 5.1; the within(TypePattern) pointcut is described in Recipe 9.1; the thisJoinPoint variable and the context it encapsulates is examined in Recipe 13.2; the after( ) and after( ) returning advice types are described in Recipes Recipe 13.5 and Recipe 13.6 respectively. |