Partilhar via


Como: Capturar exceções no código nativo lançado do MSIL

No código nativo, você pode capturar a exceção C++ nativa do MSIL. Você pode capturar exceções CLR com __try e __except.

Para obter mais informações, consulte Structured Exception Handling (C/C++) e Modern C++ best practices for exceptions and error handling.

Exemplo 1

O exemplo a seguir define um módulo com duas funções, uma que lança uma exceção nativa e outra que lança uma exceção MSIL.

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

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

Exemplo 2

O exemplo a seguir define um módulo que captura uma exceção nativa e MSIL.

// 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

Ver também

Tratamento de exceções