How to: 從 MSIL 擲回的原生程式碼中攔截例外狀況

原生程式碼,您可以攔截從 MSIL 的原生 C++ 例外狀況。您可以攔截 CLR 例外狀,以及__try和__except。

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

請參閱

其他資源

例外狀況處理 (C++ 元件擴充功能)