Pixello
Pixello

Reputation: 191

IlGenerator emits leave after throw

I'm generating a method by ilgenerator and I have a problem. IlGenerator.BeginCatchBlock() forces leave and it is unreachable instruction in this case.

using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
namespace Stack
{
    class Program
    {
        static void Main(string[] args)
        {
           var asmName = new AssemblyName("Test");
        var domain = Thread.GetDomain();
        var assembly = domain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
        var module = assembly.DefineDynamicModule("MyModule", "Test.dll", true);
        var type = module.DefineType("MyType");
        var method = type.DefineMethod("MyMethod", MethodAttributes.Public);
        var ilg = method.GetILGenerator();
        ilg.BeginExceptionBlock();
        ilg.ThrowException(typeof(Exception));
        ilg.BeginCatchBlock(typeof(Exception));
        ilg.Emit(OpCodes.Pop);
        ilg.EndExceptionBlock();
        ilg.Emit(OpCodes.Ret);
        type.CreateType();
        assembly.Save("test.dll");
        }
    }
}

Actually, output is like

 .method public instance void MyMethod () cil managed 
    {
            .maxstack 1
            .try
        {
            IL_0000: newobj instance void [mscorlib]System.Exception::.ctor()
            IL_0005: throw
            IL_0006: leave IL_0011
        } // end .try
        catch [mscorlib]System.Exception
        {
            IL_000b: pop
            IL_000c: leave IL_0011
        } // end handler
        IL_0011: ret
   }

I expected to not have leave IL_0011 at .try block. PEVerify shows no errors.

Upvotes: 2

Views: 279

Answers (0)

Related Questions