方法: MSIL からスローされるネイティブ コードの例外をキャッチする

ネイティブ コードでは、MSIL からネイティブ C++ の例外をキャッチできます。 CLR 例外は、__try__except を使用してキャッチできます。

詳細については、「構造化例外処理 (C/C++)」と「例外とエラー処理に関する最新の C++ のベスト プラクティス」を参照してください。

例 1

次のサンプルでは、2 つの関数を持つモジュールを定義します。1 つはネイティブ例外をスローし、もう 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

関連項目

例外処理