分享方式:


如何:在從 MSIL 擲回的原生程式碼中攔截例外狀況

在機器碼中,您可以從 MSIL 攔截原生 C++ 例外狀況。 您可以使用 和 __except 攔截 CLR 例外狀況 __try

如需詳細資訊,請參閱 結構化例外狀況處理 (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

另請參閱

例外狀況處理