How to: 定義和安裝全域例外處理常式

下列程式碼範例會示範如何處理的例外狀況可以擷取。該範例表單包含一個按鈕,按下時,執行會引起例外狀況擲回的 null 參考。這項功能表示一般的程式碼失敗。Main 函式所安裝的應用程式層級例外處理常式會攔截產生的例外狀況。

這是繫結至委派ThreadException事件。如此一來,後續的例外狀況會被送至App::OnUnhandled方法。

範例

// global_exception_handler.cpp
// compile with: /clr
#using <system.dll>
#using <system.drawing.dll>
#using <system.windows.forms.dll>

using namespace System;
using namespace System::Threading;
using namespace System::Drawing;
using namespace System::Windows::Forms;

ref class MyForm : public Form
{
   Button^ b;
public:
   MyForm( )
   {
      b = gcnew Button( );
      b->Text = "Do Null Access";
      b->Size = Drawing::Size(150, 30);
      b->Click += gcnew EventHandler(this, &MyForm::OnClick);
      Controls->Add(b);
   }
   void OnClick(Object^ sender, EventArgs^ args) 
   {
      // do something illegal, like call through a null pointer...
      Object^ o = nullptr;
      o->ToString( );      
   }
};

ref class App
{
public:
   static void OnUnhandled(Object^ sender, ThreadExceptionEventArgs^ e)
   {
      MessageBox::Show(e->Exception->Message, "Global Exeception");
      Application::ExitThread( );
   }
};

int main()
{
   Application::ThreadException += gcnew 
      ThreadExceptionEventHandler(App::OnUnhandled);

   MyForm^ form = gcnew MyForm( );
   Application::Run(form);
}

請參閱

其他資源

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