Dela via


Anvisningar: Fånga undantag i inbyggd kod som genereras från MSIL

I intern kod kan du fånga inbyggt C++-undantag från MSIL. Du kan fånga CLR-undantag med __try och __except.

Mer information finns i Metodtips för strukturerad undantagshantering (C/C++) och Modern C++ för undantag och felhantering.

Exempel 1

Följande exempel definierar en modul med två funktioner, en som genererar ett internt undantag och en annan som utlöser ett MSIL-undantag.

// catch_MSIL_in_native.cpp
// compile with: /clr /c
void Test() {
   throw ("error");
}

void Test2() {
   throw (gcnew System::Exception("error2"));
}

Exempel 2

Följande exempel definierar en modul som fångar ett native- och MSIL-undantag.

// catch_MSIL_in_native_2.cpp
// compile with: /clr catch_MSIL_in_native.obj
#include <iostream>
using namespace std;
void Test();
void Test2();

void Func() {
   // catch any exception from MSIL
   // should not catch Visual C++ exceptions like this
   // runtime may not destroy the object thrown
   __try {
      Test2();
   }
   __except(1) {
      cout << "caught an exception" << endl;
   }

}

int main() {
   // catch native C++ exception from MSIL
   try {
      Test();
   }
   catch(char * S) {
      cout << S << endl;
   }
   Func();
}
error
caught an exception

Se även

Undantagshantering