如何:在本机代码中捕捉从 MSIL 引发的异常
在本机代码中,则可以捕获从 MSIL 的本机 C++ 异常。可以捕获具有 __try 和 __except的 CLR 异常。
有关更多信息,请参见结构化异常处理 (C/C++)和C++ 异常处理。
示例
下面的示例定义带有两函数的本机异常,引发异常的 MSIL 和另一模块。
// catch_MSIL_in_native.cpp
// compile with: /clr /c
void Test() {
throw ("error");
}
void Test2() {
throw (gcnew System::Exception("error2"));
}
下面的示例定义捕获本机和 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();
}