Search code examples
jenkinsjenkins-pluginsjenkins-pipeline

How to throw exception in jenkins pipeline?


I have handled the Jenkins pipeline steps with try catch blocks. I want to throw an exception manually for some cases. but it shows the below error.

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new java.io.IOException java.lang.String

I checked the scriptApproval section and there is no pending approvals.


Solution

  • If you want to abort your program on exception, you can use pipeline step error to stop the pipeline execution with an error. Example :

    try {
      // Some pipeline code
    } catch(Exception e) {
      // Do something with the exception 
    
      error "Program failed, please read logs..."
    }
    

    If you want to stop your pipeline with a success status, you probably want to have some kind of boolean indicating that your pipeline has to be stopped, e.g:

        boolean continuePipeline = true
        try {
          // Some pipeline code
        } catch(Exception e) {
           // Do something with the exception 
    
           continuePipeline = false
           currentBuild.result = 'SUCCESS'
        }
    
        if(continuePipeline) {
           // The normal end of your pipeline if exception is not caught. 
        }