Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to catch an int

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?

like image 603
Nitin Chaudhari Avatar asked Apr 28 '11 05:04

Nitin Chaudhari


1 Answers

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;
}
like image 171
QrystaL Avatar answered Oct 23 '22 14:10

QrystaL