Given the following code:
using System;
using System.Linq.Expressions;
Console.WriteLine(Expression.Lambda<Func<string>>(Expression.TryFault(Expression.Constant("hi"), Expression.Constant("alternative"))).Compile()());
I am targeting net462 (repro project here).
Unhandled Exception: System.NotSupportedException: The requested operation is invalid for DynamicMethod.
at System.Reflection.Emit.DynamicILGenerator.BeginFaultBlock()
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitTryExpression(Expression expr)
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitExpression(Expression node, CompilationFlags flags)
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitLambdaBody(CompilerScope parent, Boolean inlined, CompilationFlags flags)
at System.Linq.Expressions.Compiler.LambdaCompiler.Compile(LambdaExpression lambda, DebugInfoGenerator debugInfoGenerator)
at System.Linq.Expressions.Expression`1.Compile()
at Program.<Main>$(String[] args)
Why isn’t this emission supported?
I know that my example here is not a good example of when one would want to use Expression.TryFault(). However, the semantics fit exactly what I want in a certain scenario (running some code only if an exception is thrown by a particular expression without actually catching the original exception (I am actually trying to generate a more specific exception by rerunning parts of the original expression in a bunch of try/catch with the idea that the exception case will be exceptional and rarely run)).
Why does netfx throw here? I thought that even though C# doesn’t support fault blocks, netfx did. What is DynamicMethod and why is it special? Is there any suggestion for a way to express these semantics without encountering this error?