.net2.0之杂七杂八(4)

来源:互联网 发布:快刀软件破解版 编辑:程序博客网 时间:2024/05/18 12:33

Managed Exception Handling

EH块紧跟在IL代码后(还记得方法体的结构吗),首先是一个EH头,EH头中包括KindDataSize两项。同样,EH头分smallfat,不同的是DataSize的大小,fat3字节,而small1字节。

Kind的可选值如下:

0x00Reserved

0x01EHTable(必须置位)

0x02OptILTable(未使用)

0x40FatFormat

0x80MoreSects

 

         EH头完了后,就是一串EH Clause Entries了。每个Entry的结构如下(汗,office 2007的制表功能还真不错J):

 

EH Clause Entry

Size in Small Clause

Size in Fat Clause

Flags

2

4

TryOffset

2

4

TryLength

1

4

HandlerOffset

2

4

HandlerLength

1

4

ClassToken/FilterOffset

4

4

 

         怪了,怎么没有finally块呢?其实,块的种类可以根据Flags来区别。Flags可取的值如下:

0x0000Then handler must be engaged if the type of exception object matches the type identified by the token specified in the ClassToken entry or any of this type’s descendants.

0x0001A dedicated block of the IL code, called a filter, will process the exception and define whether the handler should be engaged.

0x0002The handler will be engaged whether or not an exception has occurred.这便是finally了。

0x0004The handler will be engaged if any exception occurs.这是fault块。

 

EH有两种声明方式,Label式和Scope式。后者是我们在ildasm反编译代码中看到的形式。还可以把两种混合起来使用。形式不一样,本质是相同地。下面看一个filterlabel形式的例子(抄书的):

 

.try   {

//Guarded code

leave KeepGoing

}

filter{

//here we decide whether we should invoke the actual handler

ldc.i4.1//OK, let’s invoke the handler

endfilter

}{

//actual handler code

leave KeepGoing

}

 

         不同块中的椎栈变化如下表:

Block

进入时,椎栈

退出时,椎栈

try

为空

被抛弃

filter

包含Exception Object

10,用于endfilter进行判断

handler

包含Exception Object

被抛弃

fnally,fault

为空

被抛弃

 

 

         rethrow只能用于catch块内,且不对椎栈进行操作。

 

         四种不能被继承的异常类型:

InvalidProgramException

TypeInitializationException

Threading.ThreadAbortException

StackOverflowException

 

         OK了,异常处理介绍就到这。

 
原创粉丝点击