final CatchClause catchClause = new CatchClause(
new BlockStatement(
new ExpressionStatement(
new AssignmentExpression(
new IdentifierExpressionBackReference("savedException").toExpression(),
new NamedNode("caughtException", new IdentifierExpression(Expression.MYSTERY_OFFSET, Pattern.ANY_STRING)).toExpression()
)
),
new ThrowStatement(new IdentifierExpressionBackReference("caughtException").toExpression())
)
);
catchClause.setVariableName(Pattern.ANY_STRING);
catchClause.getExceptionTypes().add(new SimpleType("Throwable"));
tryPattern.getCatchClauses().add(catchClause);
final TryCatchStatement disposeTry = new TryCatchStatement(Expression.MYSTERY_OFFSET);
disposeTry.setTryBlock(
new BlockStatement(
new ExpressionStatement(
new IdentifierExpressionBackReference("resource").toExpression().invoke("close")
)
)
);
final CatchClause disposeCatch = new CatchClause(
new BlockStatement(
new ExpressionStatement(
new IdentifierExpressionBackReference("savedException").toExpression().invoke(
"addSuppressed",
new NamedNode("caughtOnClose", new IdentifierExpression(Expression.MYSTERY_OFFSET, Pattern.ANY_STRING)).toExpression()
)
)
)
);
disposeCatch.setVariableName(Pattern.ANY_STRING);
disposeCatch.getExceptionTypes().add(new SimpleType("Throwable"));
disposeTry.getCatchClauses().add(disposeCatch);
tryPattern.setFinallyBlock(
new BlockStatement(
new IfElseStatement( Expression.MYSTERY_OFFSET,
new BinaryOperatorExpression(
new IdentifierExpressionBackReference("resource").toExpression(),
BinaryOperatorType.INEQUALITY,
new NullReferenceExpression(Expression.MYSTERY_OFFSET)
),
new BlockStatement(
new IfElseStatement( Expression.MYSTERY_OFFSET,
new BinaryOperatorExpression(
new IdentifierExpressionBackReference("savedException").toExpression(),
BinaryOperatorType.INEQUALITY,
new NullReferenceExpression(Expression.MYSTERY_OFFSET)
),
new BlockStatement(
disposeTry
),
new BlockStatement(
new ExpressionStatement(
new IdentifierExpressionBackReference("resource").toExpression().invoke("close")
)
)
)
)
)