VOOZH about

URL: https://www.geeksforgeeks.org/java/spring-boot-aop-after-throwing-advice/

⇱ Spring Boot - AOP After Throwing Advice - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Spring Boot - AOP After Throwing Advice

Last Updated : 14 Mar, 2026

In Spring AOP, After Throwing Advice is used to execute code when a method throws an exception. It is defined using the @AfterThrowing annotation. This advice is helpful for handling errors, logging exceptions, or performing cleanup operations when something goes wrong during method execution.

  • @AfterThrowing advice runs only when the target method throws an exception.
  • It is commonly used for exception logging and error handling.
  • It helps manage errors in a centralized way without modifying business logic.

Syntax:

@Aspect
public class AfterThrowingExample {
@AfterThrowing("execution(* com.xyz.dao.*.*(..))")
public void doRecoveryActions() {
}
}

Steps to Implement After Throwing Advice

Let’s understand the steps required to implement @AfterThrowing advice in Spring AOP, which executes when a target method throws an exception.

Step 1: Create a Spring Boot Project

Open Spring Initializr and provide the following details:

  • Group: com.afterthrowing
  • Artifact: aop-afterthrowing-example
  • Dependencies: Spring Web

Download the project and extract the ZIP file.

πŸ‘ Image

Step 2: Add Dependencies in pom.xml

 Step 3: Create DAO Class

Create package com.afterthrowing.dao and add MockDAO.java.

  Step 4: Create Controller Class

Create package com.afterthrowing.controller and add DefaultWebController.java.

Step 5: Create html page

After that, we will add the index.html page under resources.templates package.


We basically access that model attribute that was passed by the DefaultWebController, as a list was passed on, we just iterate over each entry and print it out.

Step 6: Create Aspect Class

Create package com.afterthrowing.aspect and add LoggingAspect.java.

Step 7: Run the Application

Run the project using:

mvn spring-boot:run

Open the browser:

http://localhost:8080/

πŸ‘ Image
Output
πŸ‘ Image
Terminal Output
Comment
Article Tags:
Article Tags: