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

ネイティブ コードでは、 MSIL からネイティブ C++ の例外をキャッチできます。__try と __exceptCLR 例外をキャッチできます。

詳細については、「構造化例外処理 (C++)」および「C++ 例外処理」を参照してください。

使用例

次のサンプルは 2 個の関数、 1 ネイティブ例外をスロー、および 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++ コンポーネント拡張)