1

Is there a .net equivalent to the C++ unexpected()/set_unexpected() functionality?


Edit: Sorry--I omitted some details previously:

Language: C# 2.0

I have some legacy apps that seem to be throwing some unhandled exception somewhere. I just want to put something in place to stop the customer's pain until I can trace the actual source of the problem. In C++, the function pointed at by set_unexpected() gets called, as far as I know, when an otherwise unhandled exception bubbles to the main routine. Hence my question about a .net equivalent functionality.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Onorio Catenacci
  • 14,928
  • 14
  • 81
  • 132
  • Could you give more detail about what effect you're trying to achieve overall? Chances are the idiomatic way in .NET won't exactly mirror unexpected/set_unexpected. – Jon Skeet Oct 29 '08 at 14:07
  • Yes, Jon, I can see what you're saying. I realized after I posted my question that I did sort of skimp on details. I will edit appropriately. – Onorio Catenacci Oct 29 '08 at 14:20

2 Answers2

2

There 3 possible scenarios for handling unhandled exceptions, based on the type of the application:

  1. For windows forms application, hook an event handler to Application.ThreadException
  2. For commandline applications, hook an event handler to AppDomain.UnhandledException
  3. For ASP.NET applications, in Global.asax, create:

    protected void Application_Error(Object sender, EventArgs e)

DISCLAIMER: I'm not c++ developer, but from what I read, this should answer your question.

Sunny Milenov
  • 21,990
  • 6
  • 80
  • 106
0

These handlers should catch most unexpected exceptions in your mixed-mode application.

private delegate long UnhandledExceptionFilter(IntPtr exception);

[DllImport("KERNEL32.DLL", SetLastError = true)]
private static extern IntPtr SetUnhandledExceptionFilter([MarshalAs(UnmanagedType.FunctionPtr)] UnhandledExceptionFilter filter);

// put these in your bootstrapper
AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
Application.ThreadException += ApplicationThreadException;
SetUnhandledExceptionFilter(UnhandledExceptionFilter);

void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    ...
}

void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
{
    ...
}

long UnhandledExceptionFilter(IntPtr exception)
{
    ....
}
Dunc
  • 18,404
  • 6
  • 86
  • 103