Share via


如何:在本机代码中捕获从 MSIL 抛出的异常

在本机代码中,你可以从 MSIL 捕获本机 C++ 异常。 你可以使用 __try__except 捕获 CLR 异常。

有关更多信息,请参阅结构化异常处理 (C/C++)现代 C++ 处理异常和错误的最佳做法

示例 1

以下示例定义了一个具有两个函数的模块,一个函数引发本机异常,另一个函数引发 MSIL 异常。

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

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

示例 2

以下示例定义了一个模块,可捕获本机和 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

另请参阅

异常处理