how to catch an int

核能气质少年 提交于 2019-12-23 07:47:17

问题


I am using IL to throw an Int32 and catch it. This is just out of curiosity, I am not trying to achieve anything, so please dont tell me to throw an Exception instead of int.

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       40 (0x28)
  .maxstack  2
  .locals init (object V_0,
       int32 V_1)
  IL_0000:  nop
  .try
  {
    IL_0001:  nop
    IL_0002:  ldsfld     int32 ConsoleApplication3.Program::i
    IL_0007:  throw
  }  // end .try
  catch [mscorlib]System.Object 
  {
    IL_0008:  stloc.0
    IL_0009:  nop
    IL_000a:  ldstr      "In Object catch"
    IL_000f:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_0014:  nop
    IL_0015:  ldloc.0
    IL_0016:  unbox.any  [mscorlib]System.Int32
    IL_001b:  stloc.1
    IL_001c:  ldloc.1
    IL_001d:  call       void [mscorlib]System.Console::WriteLine(int32)
    IL_0022:  nop
    IL_0023:  nop
    IL_0024:  leave.s    IL_0026
  }  // end handler
  IL_0026:  nop
  IL_0027:  ret
} // end of method Program::Main

This does not work, I get the string "In Object catch" but when I try to unbox I get an System.InvalidCastException: Specified cast is not valid. How can I get the value of what was thrown?


回答1:


In version 2.0 of the CLR, when a non–CLS-compliant exception is thrown, the CLR automatically constructs an instance of the RuntimeWrappedException class and initializes its private field to refer to the object that was actually thrown. In effect, the CLR now turns all non–CLS-compliant exceptions into CLS-compliant exceptions.

try
{
    // ...
}
catch (RuntimeWrappedException e)
{
    int a = (int)e.WrappedException;
}


来源:https://stackoverflow.com/questions/5814014/how-to-catch-an-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!