Procedimiento Detectar excepciones en código nativo iniciadas desde MSIL

En código nativo, puede detectar una excepción nativa de C++ desde MSIL. Puede detectar excepciones de CLR con __try y __except.

Para obtener más información, consulte Control de excepciones estructuradas (C/C++) y Procedimientos recomendados de C++ moderno para excepciones y control de errores.

Ejemplo 1

En el ejemplo siguiente, se define un módulo con dos funciones, una que produce una excepción nativa y otra que produce una excepción de MSIL.

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

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

Ejemplo 2

En el ejemplo siguiente, se define un módulo que detecta una excepción nativa y 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();
}
error
caught an exception

Consulte también

Control de excepciones