方法: MSIL からネイティブ コードのスローされる例外をキャッチします
ネイティブ コードでは、MSIL からネイティブ C++ 例外をキャッチできます。__try と __exceptの CLR 例外をキャッチできます。
詳細については、「構造化例外処理 (C/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();
}