ILGenerator ilGenerator = methodBuilder.GetILGenerator(); Label labelTry = ilGenerator.BeginExceptionBlock(); // Here are some IL instructions inside the try block... ilGenerator.Emit(OpCodes.Ldc_I4, 42); ilGenerator.Emit(OpCodes.Div); ilGenerator.Emit(OpCodes.Ret); ilGenerator.BeginCatchBlock(typeof(DivideByZeroException)); // Here are some IL instructions inside the catch block... ilGenerator.Emit(OpCodes.Pop); ilGenerator.Emit(OpCodes.Ldc_I4_0); ilGenerator.Emit(OpCodes.Ret); ilGenerator.EndExceptionBlock();
var dynamicMethod = new DynamicMethod("MyMethod", typeof(string), null); var il = dynamicMethod.GetILGenerator(); var tryStart = il.BeginExceptionBlock(); // Here are some IL instructions inside the try block... il.Emit(OpCodes.Ldstr, "try"); il.Emit(OpCodes.Ret); var catchType = typeof(ArgumentException); var catchBlock = il.BeginCatchBlock(catchType); // Here are some IL instructions inside the catch block... il.Emit(OpCodes.Pop); il.Emit(OpCodes.Ldstr, "catch"); il.Emit(OpCodes.Ret); il.EndExceptionBlock(); // Here are some IL instructions outside the exception block... il.Emit(OpCodes.Ldstr, "finally"); il.Emit(OpCodes.Ret); var myMethod = (FuncIn this example, we create a dynamic method called MyMethod that returns a string. We use the BeginExceptionBlock method to start a try-finally block, and then we emit some IL instructions inside the try block. We also use the BeginCatchBlock method to start a catch block for the ArgumentException, and emit some IL instructions inside the catch block. Finally, we use the EndExceptionBlock method to end the exception block and emit some IL instructions outside the exception block. We then create a delegate for the dynamic method and call it to execute the IL method. The package library for System.Reflection.Emit is System.Reflection.Emit.dll which is part of the .NET Framework Class Library.)dynamicMethod.CreateDelegate(typeof(Func )); var result = myMethod();