关键字如何catch
确定抛出的异常类型?选择执行哪个 catch 块会发生什么过程?
try
{
int[] myArray = new int[0];
myArray[1] = 0;
}
catch (IndexOutOfRangeException ex) { } // how does the CLR know to enter here?
catch (InvalidCastException ex) { }
通过 ILdasm
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 28 (0x1c)
.maxstack 3
.locals init (int32[] V_0,
class [mscorlib]System.IndexOutOfRangeException V_1,
class [mscorlib]System.InvalidCastException V_2)
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: ldc.i4.0
IL_0003: newarr [mscorlib]System.Int32
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: ldc.i4.1
IL_000b: ldc.i4.0
IL_000c: stelem.i4
IL_000d: nop
IL_000e: leave.s IL_001a
} // end .try
catch [mscorlib]System.IndexOutOfRangeException
{
IL_0010: stloc.1
IL_0011: nop
IL_0012: nop
IL_0013: leave.s IL_001a
} // end handler
catch [mscorlib]System.InvalidCastException
{
IL_0015: stloc.2
IL_0016: nop
IL_0017: nop
IL_0018: leave.s IL_001a
} // end handler
IL_001a: nop
IL_001b: ret
} // end of method Program::Main
但仍不清楚该catch
关键字的作用是为了确定引发的异常类型。