try-catch在IL中如何工作?

时间:2019-02-05 14:42:02

标签: c# .net-core cil

考虑以下代码:

void Main()
{
    try {
        Console.Write("try ");
        throw new NotImplementedException();
    } 
    catch (NotImplementedException) {
        Console.Write("catch");
    }
}

使用LINQPad,我看到代码编译为:

IL_0000:  nop         
IL_0001:  nop         
IL_0002:  ldstr       "try"
IL_0007:  call        System.Console.WriteLine
IL_000C:  nop         
IL_000D:  newobj      System.NotImplementedException..ctor
IL_0012:  throw       
IL_0013:  pop         
IL_0014:  nop         
IL_0015:  ldstr       "catch"
IL_001A:  call        System.Console.WriteLine
IL_001F:  nop         
IL_0020:  nop         
IL_0021:  leave.s

上面的代码显示try catch,如果我抛出Exception,则显示try,并且由于未处理的异常(如预期的那样),该程序退出, IL < / em>代码保持不变,除了以下行:

IL_000D:  newobj      System.Exception..ctor

其背后的逻辑是什么? 除了检查异常类型以决定是否进入catch块的逻辑之外,我将不做任何事情。

0 个答案:

没有答案