ExpressionTree-TryCatch

CSharp · Console

/Program.cs

using System;
using System.Linq.Expressions;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
					
public class Program
{
	public static void Main()
	{
		Console.WriteLine("****************** C# Equivalent Output **************************\n\n");
		
        try
        {
            Console.WriteLine("Try block");
            throw new DivideByZeroException();
            Console.WriteLine("After throwing exception");
        }
        catch (DivideByZeroException d)
        {
            Console.WriteLine("Catch block");
        }

		
		Console.WriteLine("\n\n***************** Expression Tree Output **************************\n\n");

		
        var tryBlock = Expression.Block(
            WriteLineExpression("Try block"),
            Expression.Throw(Expression.Constant(new DivideByZeroException())),
            WriteLineExpression("After throwing exception")
        );

        var catchBlock = Expression.Catch(
            typeof(DivideByZeroException),
            WriteLineExpression("Catch block")
        );

        TryExpression tryCatchExpr = Expression.TryCatch(tryBlock, catchBlock);

        Expression.Lambda<Action>(tryCatchExpr).Compile()();

	}
	
    public static Expression WriteLineExpression(string s)
    {
        return Expression.Call(null,
           typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),
           Expression.Constant(s));
    }

}
;