What is the effect of @NonCPS in a Jenkins pipeline script

The exception that you are seeing is due to script security and sandboxing. Basically, by default, when you run a pipeline script, it runs in a sandbox which only allow usage of certain methods and classes. There are ways to whitelist operations, check the link above.

The @NonCPS annotation is useful when you have methods which use objects which aren’t serializable. Normally, all objects that you create in your pipeline script must be serializable (the reason for this is that Jenkins must be able to serialize the state of the script so that it can be paused and stored on disk).

When you put @NonCPS on a method, Jenkins will execute the entire method in one go without the ability to pause. Also, you’re not allowed to reference any pipeline steps or CPS transformed methods from within an @NonCPS annotated method. More information about this can be found here.

As for the exception handling: Not 100% sure what you are experiencing; I’ve tried the following and it works as expected:

@NonCPS
def myFunction() {
    throw new RuntimeException();
}

try {
    myFunction();
} catch (Exception e) {
    echo "Caught";
}

and

@NonCPS
def myFunction() {
    throw new RuntimeException();
}

def mySecondFunction() {
    try {
        myFunction();
    } catch (Exception e) {
        echo "Caught";
    }
}

mySecondFunction();

and finally:

@NonCPS
def myFunction() {
    throw new RuntimeException();
}

@NonCPS
def mySecondFunction() {
    try {
        myFunction();
    } catch (Exception e) {
        echo "Caught";
    }
}

mySecondFunction();

All print “Caught” as expected.

Leave a Comment