How to Use Try Catch in Jenkins Pipeline for Error Handling
In Jenkins Pipeline, you use
try and catch blocks inside a script or steps section to handle errors. Wrap the code that might fail in try, and handle exceptions in catch to control what happens on errors.Syntax
The try block contains code that might throw an error. The catch block catches the error and lets you handle it, like logging or setting a status. Optionally, finally runs code regardless of success or failure.
groovy
try { // code that might fail } catch (Exception e) { // handle error } finally { // code that always runs }
Example
This example shows a Jenkins Declarative Pipeline using try-catch inside a script block to catch errors during a shell command and print a message.
groovy
pipeline {
agent any
stages {
stage('Example') {
steps {
script {
try {
sh 'exit 1' // This command fails
} catch (Exception e) {
echo "Caught error: ${e.message}"
} finally {
echo 'This always runs'
}
}
}
}
}
}Output
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Example)
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ exit 1
[Pipeline] }
[Pipeline] // script
Caught error: script returned exit code 1
This always runs
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // pipeline
Common Pitfalls
- Not using
scriptblock in Declarative Pipeline when writingtry-catchcauses syntax errors. - Ignoring caught exceptions without logging can hide problems.
- Using
catchwithout specifyingException ecan cause issues. - Not using
finallywhen needed to clean up resources.
groovy
/* Wrong: try-catch outside script block in Declarative Pipeline */ pipeline { agent any stages { stage('Bad') { steps { // try-catch must be inside script block // try { // sh 'exit 1' // } catch (Exception e) { // echo "Error" // } } } } } /* Right: wrap try-catch inside script block */ pipeline { agent any stages { stage('Good') { steps { script { try { sh 'exit 1' } catch (Exception e) { echo "Error caught" } } } } } }
Quick Reference
Use try to run risky code, catch to handle errors, and finally for cleanup. Always put try-catch inside script in Declarative Pipelines.
| Keyword | Purpose | Notes |
|---|---|---|
| try | Run code that might fail | Wrap risky steps here |
| catch (Exception e) | Handle errors caught in try | Use to log or recover |
| finally | Run code always after try/catch | Good for cleanup |
| script | Wrap try-catch in Declarative Pipeline | Required for Groovy code blocks |
Key Takeaways
Always wrap try-catch blocks inside a script block in Declarative Pipelines.
Use catch to handle errors gracefully and avoid pipeline failures.
Use finally to run cleanup code regardless of success or failure.
Log exceptions inside catch to understand failures.
Try-catch helps control pipeline flow and improve reliability.