@AfterThrowing in Spring: Definition, Usage, and Examples
@AfterThrowing is an annotation in Spring AOP used to define advice that runs only when a method throws an exception. It helps you handle errors globally by executing custom logic right after a method fails.How It Works
Imagine you have a friend who always tells you when something goes wrong during a task. @AfterThrowing works like that friend in your code. It listens for exceptions thrown by methods and then runs some special code to handle those errors.
In Spring, this is part of Aspect-Oriented Programming (AOP). You write an "advice" method annotated with @AfterThrowing, and Spring automatically calls it whenever the targeted method throws an exception. This way, you can separate error handling from your main business logic, making your code cleaner and easier to maintain.
Example
This example shows how to use @AfterThrowing to log an error message when a method throws an exception.
package com.example.aspect; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; @Aspect @Component public class LoggingAspect { @AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))", throwing = "ex") public void logAfterThrowing(Exception ex) { System.out.println("Exception caught: " + ex.getMessage()); } } // Sample service class package com.example.service; import org.springframework.stereotype.Service; @Service public class SampleService { public void riskyMethod() { throw new RuntimeException("Something went wrong!"); } } // Main application to test package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import com.example.service.SampleService; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(DemoApplication.class, args); SampleService service = context.getBean(SampleService.class); try { service.riskyMethod(); } catch (Exception e) { // Exception is handled by aspect } } }
When to Use
Use @AfterThrowing when you want to run code only after a method fails with an exception. This is useful for:
- Logging errors centrally without cluttering your business code.
- Sending alerts or notifications when something goes wrong.
- Cleaning up resources or rolling back actions after failures.
For example, in a banking app, you might want to log all failed transactions or notify support when an unexpected error occurs.
Key Points
@AfterThrowingadvice runs only if the method throws an exception.- It helps separate error handling from main logic.
- You can access the thrown exception in the advice method.
- Works with Spring AOP and requires defining a pointcut to specify target methods.
Key Takeaways
@AfterThrowing runs advice only after a method throws an exception.