@Return and @Thrown Annotated-Paramaters
@Return and @Thrown Annotated-Paramaters In the same way as other advices, finally advices can receive annotated-parameters. The semantics of those parameters have been explained in the annotated-parameters and after-throwing examples. Besides everything we have seen, there are some subtleties regarding @Return and @Thrown. Firstly, if a finally advice that receives a @Thrown parameter intercepts a joinpoint that returns normally, without errors, this parameter value will be null. An example of this follows: public class FinallyAspect { public void finallyAdvice1(@Thrown Throwable thrownException) { System.out.println(">>> finallyAdvice1 Exception has been thrown: " + (thrownException != null)); } } ___________________________ The finally advice above intercepts Bank.getAccount(String) method, that throws a NoSuchAccountException if the account name is invalid. It prints a message telling whether Bank.getAccount(String) threw an exception, which happened only if thrownException is not null. Notice that the @Thrown-annotated advice parameter above is not of type NoSuchAccountException, it is of type Throwable. The reason for this is that @Thrown-annotated parameters must always be of type Throwable when declared at a finally advice. A second consideration we need to make is that, if a finally advice receives a @Return parameter, the use of @Thrown is compulsory. This is so because the @Thrown parameter indicates the validity of the @Return parameter. This way: if the joinpoint being intercepted returns normally - the @Thrown parameter value will be null and the @Return parameter will contain the joinpoint return value, as expected. If the joinpoint throws an exception - the @Thrown parameter will contain the exception and the the @Return value will invalid. The following advice also intercepts Bank.getAccount(String) method execution, but this time it prints the result if no exception has been thrown. public class FinallyAspect { public void finallyAdvice2(@Return Account account, @Thrown Throwable thrownException, @Arg String queriedName) { if (thrownException == null) { System.out.println(">>> finallyAdvice2 Account retrieved: " + account); } else { System.out.println(">>> finallyAdvice2 Account '" + queriedName + "' not found"); } } } ___________________________