Why does throwing 2 exceptions in a row not generate an unreachable code warning?

后端 未结 3 1534
失恋的感觉
失恋的感觉 2020-12-01 17:59

Why do the following lines of code not create a compiler warning?

void Main()
{
  throw new Exception();
  throw new Exception();
}

As I se

3条回答
  •  無奈伤痛
    2020-12-01 18:23

    It could give a compiler warning / error but sadly it does not. But if you look at IL code only first exception is regarded. You can log in to connect.microsoft.com and raise this as something you would like to see.

    if you ILDasm the code below

    static void Main(string[] args)
            {
                Console.Write("Line 1");
               throw new Exception(); 
               throw new Exception();
               Console.Write("Line 4");
            }
    

    You will get this

    .method private hidebysig static void  Main(string[] args) cil managed
    {
      .entrypoint
      // Code size       18 (0x12)
      .maxstack  8
      IL_0000:  nop
      IL_0001:  ldstr      "Line 1"
      IL_0006:  call       void [mscorlib]System.Console::Write(string)
      IL_000b:  nop
      IL_000c:  newobj     instance void [mscorlib]System.Exception::.ctor()
      IL_0011:  throw
    } // end of method Program::Main
    

    After the first Exception object nothing else is converted to IL.

提交回复
热议问题