ExpressionTree-TryCatchFinally

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)
        {
            Console.WriteLine("Catch block");
        }
        finally
        {
            Console.WriteLine("Finally 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")
        );

        var finallyBlock = WriteLineExpression("Finally block");

        TryExpression tryFinallyExpr = Expression.TryCatchFinally(tryBlock, finallyBlock, catchBlock);

        Expression.Lambda<Action>(tryFinallyExpr).Compile()();
	}

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