分享方式:


如何:定義與安裝全域例外狀況處理常式

下列程式碼範例示範如何擷取未處理的例外狀況。 範例表單包含按鈕,按下時會執行 Null 參考,導致擲回例外狀況。 這項功能代表一般程式碼失敗。 主函式所安裝的應用程式範圍例外狀況處理常式會攔截產生的例外狀況。

這是藉由將委派系結至 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);
}

另請參閱

例外狀況處理