Share via


방법: 네이티브 코드에서 MSIL이 throw한 예외 catch

네이티브 코드에서는 MSIL에서 네이티브 C++ 예외를 catch할 수 있습니다. 및 .를 사용하여 CLR 예외를 catch할 __try__except수 있습니다.

자세한 내용은 예외 및 오류 처리에 대한 구조적 예외 처리(C/C++)최신 C++ 모범 사례를 참조하세요.

예 1

다음 샘플에서는 네이티브 예외를 throw하는 함수와 MSIL 예외를 throw하는 함수를 포함하는 모듈을 정의합니다.

// catch_MSIL_in_native.cpp
// compile with: /clr /c
void Test() {
   throw ("error");
}

void Test2() {
   throw (gcnew System::Exception("error2"));
}

예제 2

다음 샘플에서는 네이티브 및 MSIL 예외를 catch하는 모듈을 정의합니다.

// 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

참고 항목

예외 처리