How to: Define and Install a Global Exception Handler

The following code example demonstrates how unhandled exceptions can be captured. The example form contains a button that, when pressed, performs a null reference, causing an exception to be thrown. This functionality represents a typical code failure. The resulting exception is caught by the application-wide exception handler installed by the main function.

This is accomplished by binding a delegate to the ThreadException event. In this case, subsequent exceptions are then sent to the App::OnUnhandled method.


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

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

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

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

int main()
   Application::ThreadException += gcnew

   MyForm^ form = gcnew MyForm( );

See also

Exception Handling