SoFunction
Updated on 2025-03-08

.NET(C#): Method for creating exception handling in Emit


        //+ using ;

        //+ using ;
        static void Main(string[] args)
        {
            var dm = GetMethod();

(null, new object[] { new Exception("from Mgen!") });
        }

        static DynamicMethod GetMethod()
        {

            var dm = new DynamicMethod("", null, new Type[] { typeof(Exception) });

            var ilgen = ();

            //try {

            ();

//Load the first parameter and throw

            (OpCodes.Ldarg_0);

            ();

            (typeof(Exception));

//Temporary variables and required reflection information

            var exp = (typeof(Exception));

            var msg = typeof(Exception).GetProperty("Message").GetGetMethod();

            var output = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string), typeof(object) });

//Save exception object to temporary variable exp

            (, exp);

//Format strings are put into stack

(, "Error message: {0}");

//Load temporary variables

            (, exp);

//Get Message attribute

            (, msg);

//Call the format string

            (, output);

//End the entire processing block

            ();

            ();

            return dm;

        }