private void rewriteWhenBlockForExceptionCondition(WhenBlock block) {
    List<Statement> tryStats = block.getAst();
    List<Statement> blockStats = new ArrayList<>();
    block.setAst(blockStats);

    blockStats.add(
        new ExpressionStatement(
            setThrownException(ConstantExpression.NULL)));

    // ensure variables remain in same scope
    // by moving variable defs to the very beginning of the method, they don't
    // need to be moved again if feature method also has a cleanup-block
    moveVariableDeclarations(tryStats, method.getStatements());

    TryCatchStatement tryCatchStat =
        new TryCatchStatement(
            new BlockStatement(tryStats, null),
            new BlockStatement());

    blockStats.add(tryCatchStat);

    tryCatchStat.addCatch(
        new CatchStatement(
            new Parameter(nodeCache.Throwable, SpockNames.SPOCK_EX),
            new BlockStatement(
              singletonList(
                new ExpressionStatement(
                  setThrownException(
                    new VariableExpression(SpockNames.SPOCK_EX)))),
              null)));
  }
A Spec visitor responsible for most of the rewriting of a Spec's AST.

@author Peter Niederwieser
spock-core/src/main/java/org/spockframework/compiler/SpecRewriter.java