0
0
Jenkinsdevops~5 mins

Try-catch-finally in pipelines in Jenkins - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes, parts of a Jenkins pipeline can fail. Try-catch-finally helps you handle these failures gracefully and always run cleanup steps.
When you want to catch errors in a build step and handle them without stopping the whole pipeline.
When you need to run cleanup tasks like deleting temporary files, no matter if the build succeeded or failed.
When you want to send notifications only if a part of the pipeline fails.
When you want to retry a step after catching an error.
When you want to ensure resources are released after pipeline execution.
Config File - Jenkinsfile
Jenkinsfile
pipeline {
  agent any
  stages {
    stage('Example') {
      steps {
        script {
          try {
            echo 'Running risky step'
            sh 'exit 1' // This simulates a failure
          } catch (Exception e) {
            echo "Caught error: ${e.message}"
          } finally {
            echo 'This always runs'
          }
        }
      }
    }
  }
}

This Jenkinsfile shows a pipeline with one stage that runs a risky step inside a try block.

If the step fails, the catch block runs and prints the error message.

The finally block always runs, whether the step succeeded or failed, useful for cleanup.

Commands
Check that Jenkins Job Builder is installed and working before running pipelines.
Terminal
jenkins-jobs --version
Expected OutputExpected
3.10.0
Start the Jenkins pipeline named 'example-pipeline' and wait for it to finish.
Terminal
jenkins-cli build example-pipeline -s
Expected OutputExpected
[Pipeline] Start of Pipeline [Pipeline] echo Running risky step [Pipeline] sh + exit 1 [Pipeline] echo Caught error: script returned exit code 1 [Pipeline] echo This always runs [Pipeline] End of Pipeline Finished: SUCCESS
-s - Waits for the build to complete before returning output
View the console output of the last run of the 'example-pipeline' to verify try-catch-finally behavior.
Terminal
jenkins-cli console example-pipeline
Expected OutputExpected
[Pipeline] Start of Pipeline [Pipeline] echo Running risky step [Pipeline] sh + exit 1 [Pipeline] echo Caught error: script returned exit code 1 [Pipeline] echo This always runs [Pipeline] End of Pipeline Finished: SUCCESS
Key Concept

If you remember nothing else from this pattern, remember: try-catch-finally lets you handle errors and always run cleanup steps in Jenkins pipelines.

Common Mistakes
Not using the 'script' block when writing try-catch-finally in declarative pipelines.
The try-catch-finally syntax is Groovy code and must be inside a 'script' block in declarative pipelines, otherwise it causes syntax errors.
Wrap try-catch-finally code inside a 'script' block within the steps section.
Leaving the finally block empty or missing it when cleanup is needed.
Without a finally block, cleanup steps may not run if an error occurs, causing resource leaks or stale state.
Always include a finally block for tasks that must run regardless of success or failure.
Catching generic Exception but not logging or handling it.
Swallowing errors without logging hides problems and makes debugging hard.
Log the caught exception message or take corrective action inside the catch block.
Summary
Use try-catch-finally inside a 'script' block to handle errors in Jenkins declarative pipelines.
The try block runs risky steps, catch handles errors, and finally always runs cleanup code.
This pattern helps keep pipelines stable and resources clean even when failures happen.