TryCatch() public static method

Creates a TryExpression representing a try block with any number of catch statements and neither a fault nor finally block.
public static TryCatch ( Expression body ) : TryExpression
body Expression The body of the try block.
return TryExpression
Ejemplo n.º 1
0
        public EvaluationCallback Create(Node node)
        {
            var compilerstate = new CompilerState
            {
                FunctionState = Exp.Parameter(typeof(Character), "state"),
                ErrorVariable = Exp.Parameter(typeof(bool), "error")
            };
            var result = Make(compilerstate, node);

            if (result.Type == typeof(bool))
            {
                result = ToInteger(result);
            }
            if (result.Type == typeof(int) || result.Type == typeof(float))
            {
                // int or float convert to number
                var constructor = typeof(Number).GetConstructor(new[] { result.Type });
                result = Exp.New(constructor, new[] { result });

                // wrap the evaluation in a try..catch
                var exceptionParameter = Exp.Parameter(typeof(Exception), "e");
                var writeLineMethod    = typeof(Console).GetMethod(nameof(Console.WriteLine), new Type[] { typeof(string) });
                var toStringMethod     = typeof(Exception).GetMethod(nameof(Exception.ToString));
                var catchBody          = Exp.Block(
                    Exp.Call(null, writeLineMethod, Exp.Call(exceptionParameter, toStringMethod)),
                    Exp.Constant(new Number(0)));
                result = Exp.TryCatch(result, Exp.Catch(exceptionParameter, catchBody));
                // create lambda
                var func = Exp.Lambda <Func <Character, bool, Number> >(result, compilerstate.FunctionState, compilerstate.ErrorVariable).Compile();
                return(new EvaluationCallback(o => func(o, false)));
            }
            throw new Exception();
        }
Ejemplo n.º 2
0
        public void TryCatchTypeBody()
        {
            var expected = LinqExpression.TryCatch(
                LinqExpression.Constant(0L),
                LinqExpression.Catch(
                    typeof(Exception),
                    LinqExpression.Constant(0L)));

            using var g = new GraphEngine.Graph();
            g.LoadFromString(@"
@prefix : <http://example.com/> .

:s
    :tryBody _:zero ;
    :tryHandlers (
        [
            :catchType [
                :typeName ""System.Exception"" ;
            ] ;
            :catchBody _:zero ;
        ]
    ) ;
.
_:zero
    :constantValue 0 ;
.
");
            var s = g.GetUriNode(":s");

            var actual = Expression.Parse(s).LinqExpression;

            Console.WriteLine(actual.GetDebugView());

            actual.Should().Be(expected);
        }
        public LambdaExpression CreateLambda(Type from, Type to)
        {
            var input     = Ex.Parameter(from, "input");
            var convert   = ConvertMethod(from, to);
            var exception = Ex.Parameter(typeof(Exception), "exception");
            var block     = Ex.TryCatch(
                Result(to, Ex.Call(convert, convert.GetParameters().Select(pi => getParameter(pi, input)))),
                Ex.Catch(exception, NoResult(to)));
            var lambda = Ex.Lambda(block, input);

            return(lambda);
        }
Ejemplo n.º 4
0
        public void TryCatchVariableBodyFilter()
        {
            var expected = LinqExpression.TryCatch(
                LinqExpression.Constant(0L),
                LinqExpression.Catch(
                    LinqExpression.Parameter(
                        typeof(Exception)),
                    LinqExpression.Constant(0L),
                    LinqExpression.Equal(
                        LinqExpression.Constant(0L),
                        LinqExpression.Constant(0L))));

            using var g = new GraphEngine.Graph();
            g.LoadFromString(@"
@prefix : <http://example.com/> .
@prefix xt: <http://example.com/ExpressionTypes/> .

:s
    :tryBody _:zero ;
    :tryHandlers (
        [
            :catchVariable [
                :parameterType [
                    :typeName ""System.Exception"" ;
                ] ;
            ] ;
            :catchBody _:zero ;
            :catchFilter [
                :binaryExpressionType xt:Equal ;
                :binaryLeft _:zero ;
                :binaryRight _:zero ;
            ] ;
        ]
    ) ;
.
_:zero
    :constantValue 0 ;
.
");
            var s = g.GetUriNode(":s");

            var actual = Expression.Parse(s).LinqExpression;

            Console.WriteLine(actual.GetDebugView());

            actual.Should().Be(expected);
        }
        private static Expression Expand(TryExpression expression)
        {
            var res = expression.Body;

            var handlers = default(List <CatchBlock>);

            foreach (var handler in expression.Handlers)
            {
                if (handler.Filter != null)
                {
                    if (handlers != null)
                    {
                        res      = Expression.TryCatch(res, handlers.ToArray());
                        handlers = null;
                    }

                    res = Expression.TryCatch(res, handler);
                }
                else
                {
                    if (handlers == null)
                    {
                        handlers = new List <CatchBlock>();
                    }

                    handlers.Add(handler);
                }
            }

            if (handlers != null)
            {
                res = Expression.TryCatch(res, handlers.ToArray());
            }

            if (expression.Finally != null)
            {
                res = Expression.TryFinally(res, expression.Finally);
            }

            return(res);
        }
Ejemplo n.º 6
0
        public static Expression <Func <string[], int> > WrapMain(Expression program)
        {
            LabelTarget label = Expression.Label(typeof(int));

            BlockExpression programReturningNoErrorCode = Expression.Block(program, Expression.Constant(0));

            Expression <Action <Exception> > writeLine = s => Console.Error.WriteLine(s);

            ParameterExpression exitException = Expression.Variable(typeof(ExitException));
            ParameterExpression exception     = Expression.Variable(typeof(Exception));

            TryExpression programCatchingExceptions = Expression.TryCatch(programReturningNoErrorCode,
                                                                          Expression.Catch(exitException, Expression.Property(exitException, "Code")),
                                                                          Expression.Catch(exception, Expression.Block(writeLine.eInvoke(exception), Expression.Constant(1))));

            LabelExpression returnLabel = Expression.Label(label, programCatchingExceptions);

            ParameterExpression parameter             = Expression.Parameter(typeof(string[]), "args");
            Expression <Func <string[], int> > lambda = Expression.Lambda <Func <string[], int> >(returnLabel, parameter);

            return(lambda);
        }
Ejemplo n.º 7
0
        static void Main()
        {
            var asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("bar"), AssemblyBuilderAccess.Save);
            var mod = asm.DefineDynamicModule("bar.dll");
            var typ = mod.DefineType("Foo");

            var lblRet = Expression.Label(typeof(int));
            var lbl1   = Expression.Label(typeof(int));
            var ex     = Expression.Parameter(typeof(Exception));

            var expressions = new Expression[]
            {
                Expression.TryFault(
                    Expression.Constant(1),
                    Expression.Constant(2)
                    ),
                Expression.Block(
                    Expression.TryFault(
                        Expression.Goto(lblRet, Expression.Constant(1)),
                        Expression.Constant(2)
                        ),
                    Expression.Label(lblRet, Expression.Constant(0))
                    ),
                Expression.Block(
                    Expression.TryFault(
                        Expression.Block(
                            Expression.Goto(lblRet, Expression.Constant(1)),
                            Expression.Constant(2)
                            ),
                        Expression.Constant(3)
                        ),
                    Expression.Label(lblRet, Expression.Constant(0))
                    ),
                Expression.Block(
                    Expression.TryFault(
                        Expression.Block(
                            Expression.Goto(lbl1, Expression.Constant(1)),
                            Expression.Goto(lblRet, Expression.Constant(2))
                            ),
                        Expression.Constant(3)
                        ),
                    Expression.Label(lbl1, Expression.Constant(-1)),
                    Expression.Label(lblRet, Expression.Constant(0))
                    ),
                Expression.TryCatch(
                    Expression.Constant(1),
                    Expression.Catch(ex, Expression.Constant(2), Expression.Constant(true))
                    ),
            };

            var i = 0;

            foreach (var expression in expressions)
            {
                var mtd = typ.DefineMethod("M" + i, MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[0]);
                Expression.Lambda <Func <int> >(expression).CompileToMethod(mtd);

                var cw = Expression.Lambda <Func <int> >(expression).CompileWithExceptionHandling();
                cw();

                i++;
            }
        }
        public void MiscellaneousExpression_Try()
        {
            var tryCatch = Expr.TryCatch(Expr.Constant(false), Expr.Catch(typeof(Exception), Expr.Constant(false)));

            UnsupportedExpr(Property.Id, id => tryCatch, ExpressionType.Try);
        }
Ejemplo n.º 9
0
 public override SysExpr ToExpression() =>
 Finally == null?SysExpr.TryCatch(Body.ToExpression(), ToCatchBlocks(Handlers)) :
     Handlers == null?SysExpr.TryFinally(Body.ToExpression(), Finally.ToExpression()) :
         SysExpr.TryCatchFinally(Body.ToExpression(), Finally.ToExpression(), ToCatchBlocks(Handlers));
Ejemplo n.º 10
0
 public static Expression TryNoCatch(this Expression expression)
 => Expression.TryCatch(expression, Expression.Catch(typeof(Exception).ToParameter(), Expression.Empty()));