3

I am developing a WPF .net 3.5 application which is using other modules/libraries created within a company. Not all of them support logging and sometimes the information about handled exceptions may be quite useful to find out what's wrong. So the question is if I can get any notification or hookup somehow for handled events in other modules?

Thanks.

Alex Semenov
  • 136
  • 5
  • 1
    See also http://stackoverflow.com/questions/256548/is-there-a-way-to-log-or-intercept-first-chance-exceptions – Wim Coenen Nov 17 '10 at 15:04
  • 1
    It's not as easy as hooking an event, but there are ways to trap them. Unfortunately it requires some pretty low-level hackery and may impact performance. See here: http://stackoverflow.com/questions/952304/net-first-chance-exception-listener-for-intensive-debugging – Dan Bryant Nov 17 '10 at 15:08
  • These questions make me wonder if there would be demand for a tool that would ildasm an assembly, list all locations where exceptions are swallowed and provide an automatic rewriter to inject a call to logging code (or even force the exception to rethrow for the purposes of debugging). Sort of like AOP systems, but designed to work with unannotated DLLs as a way to deal with misbehaving third-party code. – Dan Bryant Nov 17 '10 at 15:16
  • The tool would be quite useful at least for debugging purposes. – Alex Semenov Nov 17 '10 at 15:18

2 Answers2

5

In net 4.0 and above, there is a solution:
The event AppDomain.FirstChanceException fires before any catch block is executed.

This MSDN article has some examples.

Basically you just add an event handler like this:

    AppDomain.CurrentDomain.FirstChanceException += 
        (object source, FirstChanceExceptionEventArgs e) =>
        {
            Console.WriteLine("FirstChanceException event raised in {0}: {1}",
                AppDomain.CurrentDomain.FriendlyName, e.Exception.Message);
        };
HugoRune
  • 13,157
  • 7
  • 69
  • 144
2

There are two events, Application.DispatcherUnhandledException and AppDomain.CurrentDomain.UnhandledException, which might help you. Otherwise, I think, you are out of luck, especially if the modules handle the exceptions themself. Only way would be to attach a debugger, as First-Chance exceptions show up there.

Femaref
  • 60,705
  • 7
  • 138
  • 176