Compartilhar via


Como: capturar exceções no código nativo jogado de MSIL

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

Para obter mais informações, consulte Tratamento de exceções estruturado (C/C++) e Tratamento de exceções C++.

Exemplo

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

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

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

O exemplo a seguir define um módulo que captura um nativo e a exceção de 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();
}
  

Consulte também

Outros recursos

Tratamento de Exceção (Extensões de Componentes C++)