Search in sources :

Example 1 with CpsFunction

use of com.cloudbees.groovy.cps.impl.CpsFunction in project groovy-cps by cloudbees.

the class BasicTest method exceptionStackUnwinding.

/**
     * An exception thrown in a function caught by another function
     */
@Test
public void exceptionStackUnwinding() {
    class Op {

        /**
             * if (0<depth)
             *      throw_(depth-1,message);
             * else
             *      throw new IllegalArgumentException(message)
             */
        public void throw_(int depth, String message) {
            Block $depth = b.localVariable("depth");
            CpsFunction f = new CpsFunction(asList("depth", "message"), b.block(b.if_(b.lessThan(0, b.zero(), $depth), b.functionCall(0, b.this_(), "throw_", b.minus(0, $depth, b.one()), b.localVariable("message")), // else
            b.throw_(0, b.new_(0, IllegalArgumentException.class, b.localVariable("message"))))));
            throw new CpsCallableInvocation(f, this, depth, message);
        }
    }
    /*
            int x;
            try {
                x = 1;
                new Op().throw_(3,"hello")
                x = 2; // make sure this line gets skipped
            } catch (Exception e) {
                return e.message + x;
            }
         */
    assertEquals("hello1", run(// part of the test is to ensure this 'z' is separated from 'z' in the add function
    b.setLocalVariable(0, "x", b.zero()), b.tryCatch(b.block(b.setLocalVariable(0, "x", b.one()), b.functionCall(0, b.constant(new Op()), "throw_", b.constant(3), b.constant("hello")), b.setLocalVariable(0, "x", b.two())), null, new CatchExpression(Exception.class, "e", b.return_(b.plus(0, b.property(0, b.localVariable("e"), "message"), b.localVariable("x")))))));
}
Also used : CpsCallableInvocation(com.cloudbees.groovy.cps.impl.CpsCallableInvocation) CpsFunction(com.cloudbees.groovy.cps.impl.CpsFunction) InvocationTargetException(java.lang.reflect.InvocationTargetException) Test(org.junit.Test)

Aggregations

CpsCallableInvocation (com.cloudbees.groovy.cps.impl.CpsCallableInvocation)1 CpsFunction (com.cloudbees.groovy.cps.impl.CpsFunction)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Test (org.junit.Test)1