Consider this Jenkins scripted pipeline snippet using try-catch-finally:
node {
try {
echo 'Start build'
error 'Build failed'
} catch (Exception e) {
echo "Caught error: ${e.message}"
} finally {
echo 'Cleanup actions'
}
}What will Jenkins print in the console?
node {
try {
echo 'Start build'
error 'Build failed'
} catch (Exception e) {
echo "Caught error: ${e.message}"
} finally {
echo 'Cleanup actions'
}
}Remember that error throws an exception caught by catch, and finally always runs.
The error step throws an exception with message 'Build failed'. The catch block catches it and prints the message. The finally block always runs after try or catch, so 'Cleanup actions' is printed last.
Choose the correct statement about the behavior of try-catch-finally blocks in Jenkins scripted pipelines.
Think about how exceptions propagate and how finally always runs.
The catch block catches any exception thrown in the try block. The finally block always runs regardless of success or failure. Errors in finally are not ignored and will fail the build.
Given this Jenkins scripted pipeline snippet, order the steps as Jenkins executes them:
node {
try {
echo 'Step 1'
error 'Fail here'
echo 'Step 2'
} catch (Exception e) {
echo 'Step 3'
} finally {
echo 'Step 4'
}
echo 'Step 5'
}Remember that after error is called, the rest of try block is skipped.
Jenkins runs 'Step 1', then hits error which throws an exception. 'Step 2' is skipped. The catch block runs printing 'Step 3'. Then finally runs printing 'Step 4'. After finally, the pipeline continues with 'Step 5'. But 'Step 5' is outside try-catch-finally and runs normally. However, since the error was caught, the pipeline continues. So the order is 1,2 (error), 4 (catch), 5 (finally), 6 (after finally). Option C (1,2,4,5,6) matches this correct order.
Look at this Jenkins scripted pipeline snippet:
node {
try {
echo 'Build started'
sh 'exit 1'
} catch (Exception e) {
echo 'Caught error'
} finally {
sh 'exit 1'
echo 'Cleanup'
}
}Why does Jenkins fail without printing 'Cleanup'?
Consider the order of commands in finally and what happens if a shell command fails.
The shell command sh 'exit 1' in finally causes the pipeline to fail immediately, so the next line echo 'Cleanup' is never reached. The catch block runs before finally, so it does catch the first error. But errors in finally are not caught and stop the pipeline.
In Jenkins scripted pipelines, you want to ensure cleanup commands always run, and even if a cleanup command fails, the pipeline continues to run all cleanup steps. Which pattern achieves this?
Think about how to handle errors inside finally to avoid stopping cleanup early.
Errors inside finally stop the pipeline immediately, so to ensure all cleanup commands run, each should be wrapped in its own try-catch inside finally. This way, if one cleanup command fails, others still run.