How to clean up after task B is done (success or failure but should do some cleanup )

So the issue is that the dependency is failing, but I want to do some cleanup after B is executed, no matter whether B was failed or successful, whether the dependencies were failed or successfull. It should always call the clean up… some thing like try catch and finally, but I dont want to use try catch. Is there any clean way to do that. Here’s the example

gradle.taskGraph.afterTask { Task task, TaskState state ->
    if( == 'B') {
      println " Cleanup.............";
    task C << {
  throw new Exception("MockException");
task A(dependsOn: C) {
task B(dependsOn: A)

partial output

  FAILURE: Build failed with an exception.
  * Where:
Build file '/srcroot/build.gradle' line: 837
  * What went wrong:
Execution failed for task ':C'.
> java.lang.Exception: MockException
  * Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

what I tried was ./gradlew B

The documentation on gradle site says

“The following example logs the start and end of each task execution. Notice that the afterTask notification is received regardless of whether the task completes successfully or fails with an exception.”


but in this case the parent task B is not failing, but the dependencies are failing. But I still want to do clean up since it was directed from task B

Just found that there is a plan to add finalizer task in gradle

more details here…

Why do you want to clean up a task that hasn’t run? How can there possibly be something to clean up for this task? Can you explain the deeper problem that you are trying to solve? There might be a different solution.

Ohhk, so the problem was something like try{} catch{} finally{}, no matter what happened in try (whether successful execution, or throwing error) it should always execute finally.

An example would be having some kind of integration test suite which has some spin up, and some tear down, where the spin up is bringing up multiple components. However, upon thinking about it a little more, i think the answer is to split the spin-up task into multiple tasks, and have each task have a respective finalizedBy task. it seems like finalizedBy runs on success or failure.

Hey, with a current gradle version you can declare a finalizer task to do the cleanup:

taskB.finalizedBy cleanUpB