How to: 從 MSIL 擲回的原生程式碼中攔截例外狀況
在機器碼中,您可以攔截 MSIL 的原生 C++ 例外狀況。您可以攔截與 __try 和 __except的 CLR 例外狀況。
如需詳細資訊,請參閱結構化例外狀況處理 (C/C++)與C++ 例外狀況處理。
範例
下列範例定義具有兩個函式的,擲回原生例外狀況擲回之例外狀況的和類別的模組。
// 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();
}