Exception Handling is alsoProgramIs an important partIlWriting Exception HandlingCodeFirst, the class to be implemented is provided as an example.C #The Code is as follows:
Exceptionhandler
Class Exceptionhandler
{
Public Static Int Converttoint32 ( String Str)
{
Int Num = 0 ;
Try
{
Num = Convert. toint32 (STR );
}
Catch (Exception ex)
{
Console. writeline (ex. Message );
}
Return Num;
}
}
the code is relatively simple, it mainly describes how to IL MSO-Hansi-font-family: "Times New Roman" "> Add try "Times New Roman" ">, catch block. ilgenerator several new methods in the class, introduction:
L
beginexceptionblock "Times New Roman" ">: indicates the beginning of the Code for exception handling, which is equivalent to C # "Times New Roman" "> try "Times New Roman" "> keywords;
L
Endexceptionblock : Beginexceptionblock Pairing indicates the end of exception handling. Note: The end here is not just Try The end of the statement block refers to the entire Try catch The end of the statement block;
L
Begincatchblock : Indicates Catch At the beginning of the operation, this method needs to be passed in the type of a field to be captured, the program can have multiple Begincatchblock , That is, multiple Catch Block.
The related code is as follows:
Exception
Typebuilder = Modulebuilder. definetype ( " Exceptionhandler " , Typeattributes. Public );
methodbuilder = typebuilder. definemethod ( " convertint32 " , methodattributes. public | methodattributes. static, typeof (int32 ), New type [] { typeof ( string )});
Ilgenerator methodil=Methodbuilder. getilgenerator ();
Localbuilder num=Methodil. declarelocal (Typeof(Int32 ));
//Int num = 0;
Methodil. emit (Opcodes. ldc_i4_0 );
Methodil. emit (Opcodes. stloc_0 );
// Begin try
Label trylabel = Methodil. beginexceptionblock ();
// Num = convert. toint32 (STR );
Methodil. emit (Opcodes. ldarg_0 );
Methodil. emit (Opcodes. Call, Typeof (Convert). getmethod ( " Toint32 " , New Type [] { Typeof ( String )}));
Methodil. emit (Opcodes. stloc_0 );
// End try
// Begin catch Note: At this time, the top of the stack is exception information ex
Methodil. begincatchblock ( Typeof (Exception ));
// Console. writeline (ex. Message );
Methodil. emit (Opcodes. Call, Typeof (Exception). getmethod ( " Get_message " ));
Methodil. emit (Opcodes. Call, Typeof (Console). getmethod ( " Writeline " , New Type [] { Typeof ( String )}));
// End catch
Methodil. endexceptionblock ();
//Return num;
Methodil. emit (Opcodes. ldloc_0 );
Methodil. emit (Opcodes. Ret );
Type type=Typebuilder. createtype ();
Assemblybuilder. Save (filename );
download Source Code MSO-Fareast-font-family:; MSO-font-kerning: 6.5pt; MSO-ANSI-language: En-US;
MSO-Fareast-language: ZH-CN; MSO-bidi-language: AR-SA "> "Times New Roman" "> Exception Handling