[jenkins] Try-catch block in Jenkins pipeline script

I'm trying to use the following code to execute builds, and in the end, execute post build actions when builds were successful. Still, I get a MultipleCompilationErrorsException, saying that my try block is Not a valid section definition. Please help, I tried a lot reorganize the block but can't seem to be able to solve the issue.

#!/usr/bin/env groovy

pipeline{

agent any 
    try {
        stages{
            stage("Parallel 1") {
                steps {
                    parallel (
                       'firstTask' : { 
                            build( "DSL-Controll-Demo-Fibonacci-1" )
                        },
                        'secondTask' : { 
                            build( "DSL-Controll-Demo-Fibonacci-2" )
                        }
                    )
                }
            }
            stage("Feature") {
                steps {
                        build( "DSL-Controll-Demo-Fibonacci-5" )
                        build( "DSL-Controll-Demo-Fibonacci-6" )
                }
            }
            stage("Parallel 2") {
                steps{
                    parallel (
                        "thirdTask" : { 
                            build( "DSL-Controll-Demo-Fibonacci-3" )
                        },
                        "forthTask" : { 
                            build( "DSL-Controll-Demo-Fibonacci-4" )
                        }
                    )
                }
            }
        }
    }   

    catch(all) {
        currentBuild.result = 'FAILURE'
    }   

    if(currentBuild.result != 'FAILURE') {
        stages{
            stage("Post Build") {
                steps {
                    build("DSL-Controll-Demo-Fibonacci-7")
                }   
            }   
        }
    }
}

This question is related to jenkins groovy try-catch jenkins-pipeline

The answer is


Look up the AbortException class for Jenkins. You should be able to use the methods to get back simple messages or stack traces. In a simple case, when making a call in a script block (as others have indicated), you can call getMessage() to get the string to echo to the user. Example:

script {
        try {
            sh "sudo docker rmi frontend-test"
        } catch (err) {
            echo err.getMessage()
            echo "Error detected, but we will continue."
        }
        ...continue with other code...
}

try/catch is scripted syntax. So any time you are using declarative syntax to use something from scripted in general you can do so by enclosing the scripted syntax in the scripts block in a declarative pipeline. So your try/catch should go inside stage >steps >script.

This holds true for any other scripted pipeline syntax you would like to use in a declarative pipeline as well.


This answer worked for me:

pipeline {
  agent any
  stages {
    stage("Run unit tests"){
      steps {
        script {
          try {
            sh  '''
              # Run unit tests without capturing stdout or logs, generates cobetura reports
              cd ./python
              nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
              cd ..
              '''
          } finally {
            junit 'nosetests.xml'
          }
        }
      }
    }
    stage ('Speak') {
      steps{
        echo "Hello, CONDITIONAL"
      }
    }
  }
}

try like this (no pun intended btw)

script {
  try {
      sh 'do your stuff'
  } catch (Exception e) {
      echo 'Exception occurred: ' + e.toString()
      sh 'Handle the exception!'
  }
}

The key is to put try...catch in a script block in declarative pipeline syntax. Then it will work. This might be useful if you want to say continue pipeline execution despite failure (eg: test failed, still you need reports..)


Examples related to jenkins

Maven dependencies are failing with a 501 error Jenkins pipeline how to change to another folder Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding How to solve npm install throwing fsevents warning on non-MAC OS? Run bash command on jenkins pipeline Try-catch block in Jenkins pipeline script How to print a Groovy variable in Jenkins? Jenkins pipeline if else not working Error "The input device is not a TTY"

Examples related to groovy

Jenkins pipeline how to change to another folder groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding Run bash command on jenkins pipeline Try-catch block in Jenkins pipeline script How to print a Groovy variable in Jenkins? Jenkins pipeline if else not working How to set and reference a variable in a Jenkinsfile Jenkins: Can comments be added to a Jenkinsfile? How to define and use function inside Jenkins Pipeline config? Jenkins: Cannot define variable in pipeline stage

Examples related to try-catch

Try-catch block in Jenkins pipeline script Error handling with try and catch in Laravel sql try/catch rollback/commit - preventing erroneous commit after rollback IsNumeric function in c# Why is "except: pass" a bad programming practice? EOFException - how to handle? How to efficiently use try...catch blocks in PHP How to return a value from try, catch, and finally? Multiple try codes in one block Catch KeyError in Python

Examples related to jenkins-pipeline

Jenkins pipeline how to change to another folder Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock Try-catch block in Jenkins pipeline script How to print a Groovy variable in Jenkins? Error "The input device is not a TTY" How to set and reference a variable in a Jenkinsfile Get git branch name in Jenkins Pipeline/Jenkinsfile Jenkins: Can comments be added to a Jenkinsfile? How to define and use function inside Jenkins Pipeline config? Environment variable in Jenkins Pipeline