Throwing exception in @Before, catching in @AfterThrowing
Frage
I created a @Before Advice that throws an exception and tried to catch it in another @AfterThrowing, but it does not work.
If the exception is not thrown in the advice, but directly in the method, it works.
If it is thrown in the advice, the @AfterThrowing is not executed.
Why does it behave like that?
Lösung
Because @AfterThrowing
means: catch the event that an exception is thrown from within the captured method. But @Before
means: do something before (i.e. outside) the captured method. So your control flow never reaches a point where it could satisfy the condition for the @AfterThrowing
advice.
So either you do what Frank told you (use an @Around
advice) or, if you have control over the caller as well as the callee part of the code, you could do this (quite ugly):
@Before("execution(myMethod)")
(possibly throwing an exception)AfterThrowing("call(myMethod)")
I have not tested it, but it should work because of this control flow:
[before call]
call(myMethod)
[before execution]
execution(myMethod)
[after execution]
[after call]
I.e. "before execution" is already "within call".
Andere Tipps
I suppose the 2 advices are in same aspect? If not, have you declared a precedence to define the weaving order?
Anyway, if you want to do something before a method, and something after depending on what you did before, you should be using an @Around
advice instead. You might not even need an exception (which is costly) to control the flow that way.