Export (0) Print
Expand All

14.2 try/catch

Visual Studio .NET 2003

A single C++ try/catch block can be used to catch both managed and unmanaged exceptions.

Example

// mcpp_eh2.cpp
// compile with: /clr /EHsc
#using <mscorlib.dll>
using namespace System;
__gc struct G : System::Exception { int i; };

struct Cclass { double d; };

void f() { G * pG = new G; pG->i = 11; throw pG; };

void g() {
   Cclass c = {2.0};
   throw c;
};

int main() {
   for (int i = 2 ; i > 0 ; --i )    {
      try {
         if ( i == 1)
            f();
         if ( i == 2)
            g();
      }
      catch(Cclass& catchC) {
         Console::WriteLine(catchC.d);
      }

      catch(G* catchG) {
         Console::WriteLine(catchG->i);
      }
   }
}

Output

2
11

Unwinding occurs for any C++ objects with destructors that are on the runtime stack between the throwing function and the handling function when C++ exception handling (/EHsc) is enabled. Since __gc classes are allocated on the heap, unwinding does not apply to them.

Constraint

  • The result object of a catch clause or throw statement shall not be an unboxed value type.

Example

// mcpp_eh3.cpp
// compile with: /clr
#using <mscorlib.dll>
__value struct V { int i; };

void f() {
   V v = {9};
   throw v;   // C2715 cannot throw unboxed value type
};

void g() {
   V v = {11};
   throw __box(v);   // ok
};

int main() {
   try {
      g();
   }
   catch( __box V * pbV) {
      System::Console::WriteLine(pbV -> I);
   }
}
Show:
© 2014 Microsoft