本篇讲解怎么生成异常。C# 异常处理时建立在四个关键词之上的:try、catch、finally 和 throw。

一、异常的抛出
抛出异常在C#语言中要使用throw关键字,使用方法是
throw <一个异常对象>;

throw;

1、抛出异常
抛出异常的指令是Throw,它对应的C#使用语句是
throw new <异常类型>;

它的使用格式是
adderIL.ThrowException(<异常Type>);

它的生成步骤是
(1)用newobj指令创一个异常对象
(2)生成Throw指令

2、再次抛出异常
抛出异常的指令是Rethrow,它对应的C#语句是
throw;
这条语句只有一个关键字“throw”和封号,所以它只能用在catch语句块,是把捕捉到的异常再次抛出。

二、异常的处理
C#语言的异常处理是try...catch...finally语句。
它的生成步骤是

1.用DefineLabel创建一个异常处理结束的标签。

2、生成try
这要使用BeginExceptionBlock方法,返回一个Label对象。

3、生成catch
这要使用BeginCatchBlock方法,有一个参数,它代表所要捕捉的异常类型。
实例:
ilGenerator.BeginCatchBlock(typeof(ArgumentNullException));

4、生成finally
这要使用BeginFinallyBlock方法。

5、结束异常
这要使用EndExceptionBlock方法。

6、标记异常处理结束

完整程序:

using System;
using System.Reflection;
using System.Reflection.Emit; namespace LX1_ILDemo
{
class Demo26_TryCatchFinally
{
static string binaryName = "Demo26_TryCatchFinally.exe";
static string namespaceName = "LX1_ILDemo";
static string typeName = "DemoTryCatchFinally"; static AssemblyBuilder assemblyBuilder;
static ModuleBuilder moduleBuilder;
static TypeBuilder typeBuilder;
static MethodBuilder mainMethod;
static MethodBuilder testMethod; static void Emit_TestMethod()
{
testMethod = typeBuilder.DefineMethod("Test", MethodAttributes.Public
| MethodAttributes.Static, typeof(void), new Type[] { typeof(string)});
ILGenerator ilGenerator = testMethod.GetILGenerator(); Label endOfMethodLabel = ilGenerator.DefineLabel(); Label exceptionBlock = ilGenerator.BeginExceptionBlock();
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Call, typeof(int).GetMethod("Parse", new Type[] { typeof(string) }));
ilGenerator.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(int) }));
//ilGenerator.Emit(OpCodes.Leave_S, endOfMethodLabel); ilGenerator.BeginCatchBlock(typeof(ArgumentNullException));
ilGenerator.Emit(OpCodes.Pop);
ilGenerator.EmitWriteLine("error");
ilGenerator.Emit(OpCodes.Rethrow);
//ilGenerator.Emit(OpCodes.Leave_S, endOfMethodLabel); ilGenerator.BeginFinallyBlock();
ilGenerator.EmitWriteLine("finally");
MethodInfo readKeyMethod = typeof(Console).GetMethod("ReadKey", new Type[] { });
ilGenerator.Emit(OpCodes.Call, readKeyMethod);
ilGenerator.Emit(OpCodes.Pop); ilGenerator.EndExceptionBlock(); ilGenerator.MarkLabel(endOfMethodLabel);
ilGenerator.Emit(OpCodes.Ret);
} public static void Generate()
{
InitAssembly();
typeBuilder = moduleBuilder.DefineType(namespaceName + "." + typeName, TypeAttributes.Public); Emit_TestMethod();
GenerateMain(); assemblyBuilder.SetEntryPoint(mainMethod, PEFileKinds.ConsoleApplication);
SaveAssembly();
Console.WriteLine("生成成功");
} static void GenerateMain()
{
mainMethod = typeBuilder.DefineMethod("Main", MethodAttributes.Public
| MethodAttributes.Static, typeof(void), new Type[] { });
var ilGenerator = mainMethod.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldstr,"10t");
ilGenerator.Emit(OpCodes.Call, testMethod); MethodInfo readKeyMethod = typeof(Console).GetMethod("ReadKey", new Type[] { });
ilGenerator.Emit(OpCodes.Call, readKeyMethod);
ilGenerator.Emit(OpCodes.Pop); ilGenerator.Emit(OpCodes.Ret);
} static void InitAssembly()
{
AssemblyName assemblyName = new AssemblyName(namespaceName);
assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, binaryName);
} static void SaveAssembly()
{
Type t = typeBuilder.CreateType(); //完成Type,这是必须的
assemblyBuilder.Save(binaryName);
}
}
}

MSIL实用指南-生成异常处理的更多相关文章

  1. MSIL实用指南-生成索引器

    MSIL实用指南-生成索引器 索引器是一种特殊的属性,它有参数的,也有get和set方法,属性名称一般是"Item",并且方法名称一般名称是"get_Item" ...

  2. MSIL实用指南-生成属性

    本篇讲解怎么生成属性,包括get和set方法. 第一步,生成一个字段生成字段用TypeBuilder.DefineField方法.实例代码: FieldBuilder customerNameBldr ...

  3. MSIL实用指南-生成构造函数

    本篇讲解生成构造函数的一些知识,包括创建实例构造函数.静态构造函数.调用父类构造函数. 生成构造函数的方法生成构造函数的方法是TypeBuilder.DefineConstructor(MethodA ...

  4. MSIL实用指南-生成接口

    本篇讲解怎么样生成接口,即interface. 一.创建类型创建一个接口类型依旧用ModuleBuilder的DefineType方法,但是它的第二个参数必须要有TypeAttributes.Inte ...

  5. MSIL实用指南-生成if...else...语句

    if...else...语句是非常重要的选择语句,它的生成一般需要ILGenerator的DefineLabel方法和MarkLabel方法,以及Brtrue_S和Br_S指令. 一.DefineLa ...

  6. MSIL实用指南-生成内部类

    生成内部类用TypeBuilder的DefineNestedType方法,得到另一个TypeBuilder.内部类的可访问性都是TypeAttributes的“Nested”开头一些成员.实例代码:y ...

  7. MSIL实用指南-生成foreach语句

    foreach可以迭代数组或者一个集合对象.foreach语句格式是它的生成步骤是foreach (<成员> in <集合>) <循环体> 一.声明三个变量,loc ...

  8. MSIL实用指南-生成for语句

    for语句格式是这样的for(<初始化语句>;<条件语句>;<自增减语句>) <循环体> 它可以转换为while语句 if(<条件语句>){ ...

  9. MSIL实用指南-生成while语句

    本篇讲解怎样生成while语句.while语句是编程语言中很重要的循环语句,它的结构是while(<表达式>) <语句或语句块> 当表达式的结果为true时就一直执行语句或语句 ...

随机推荐

  1. 《VR入门系列教程》之4---运行平台

    运行平台     大多数的VR应用都可以在目前多数的PC和手机上运行,基本上一个不太旧的PC或者配置好点的笔记本电脑都可以正常运行Oculus Rift,如果手机的CPU和显卡不错的话也可以有很好的V ...

  2. swift对象存储

    swift对象存储 简介 OpenStack Object Storage(Swift)是OpenStack开源云计算项目的子项目之一,被称为对象存储,提供了强大的扩展性.冗余和持久性.对象存储,用于 ...

  3. 私有网络(VPC)概述

    1 什么是私有网络(VPC) 私有网络是一块可用户自定义的网络空间,您可以在私有网络内部署云主机.负载均衡.数据库.Nosql快存储等云服务资源.您可自由划分网段.制定路由策略.私有网络可以配置公网网 ...

  4. Win常用软件

    本节只适合windows系统 VScode 下载 安装 双击安装 打开目录方式 右键文件夹->使用VSCode打开 命令行打开 code folder [dzlua@win10:~]$ ls a ...

  5. Java中内部类的骚操作

      10.1 如何定义内部类 如代码10.1-1 所示 public class Parcel1 { public class Contents{ private int value = 0;​ pu ...

  6. 非UI线程更新界面

    package com.caterSys.Thread; import java.text.SimpleDateFormat; import java.util.Date; import org.ec ...

  7. 通过自制yum源离线安装ansible

    系统环境 --CentOS release 7 python版本--Python 3.5.4   背景:在企业环境中,安装ansible的服务器往往不能访问互联网,简单的下载ansible源码安装,会 ...

  8. 用 PYQT5 和 QT Dseingner 写的串口助手

    最近公司做项目需要写串口助手,于是从网上找教程着手写了一下,基本的功能可以实现了,但是想要一个表盘的功能一直没有找到教程,有些遗憾.大神们会的话给指导指导  谢谢啦 ! 下边有源码的连接,欢迎大家下载 ...

  9. RocketMQ中Broker的HA策略源码分析

    Broker的HA策略分为两部分①同步元数据②同步消息数据 同步元数据 在Slave启动时,会启动一个定时任务用来从master同步元数据 if (role == BrokerRole.SLAVE) ...

  10. java并发编程(十三)----(JUC原子类)引用类型介绍(CAS和ABA的介绍)

    这一节我们将探讨引用类型原子类:AtomicReference, AtomicStampedRerence, AtomicMarkableReference.AtomicReference的使用非常简 ...