Short of using a profiler, is there any way inside a running program to detect first chance exceptions? Ideally, I would like to record more detailed state information that is not available once the catch block has taken over the final exception.
A first chance exception occurs when an exception is thrown and there is no catch block to handle it. Enablying first chance exceptions stops the debugger whenever an exception is thrown whether there is a catch block or not.
If the application does not handle the exception, the debugger is re-notified. This is known as a "second chance" exception. The debugger again suspends the application and determines how to handle this exception.
The FirstChanceException event of the AppDomain class lets you receive a notification that an exception has been thrown, before the common language runtime has begun searching for exception handlers. The event is raised at the application domain level.
I was googling FirstChanceException, and I can't resist answering this more than two years later...
Now, in .net 4.0, you can catch the FirstChanceException event of the AppDomain. It is an event only, so you can't handle the error, but it seems to be a good, central way to get information on exceptions whether they are handled or not. The FirstChanceException event is thrown before a catch block is allowed to handle it. I haven't found a lot of information on it, but aside from the microsoft documentation, one of the better sources is Mitch Sellers Blog.
I think the only way you can get that information in .NET is using a Debugger.
Otherwise, you'll have to develop a solution yourself for saving the state of a stackframe and having a special way to log exceptions. You'd basically be doing the same things that a memory profiler does, keep track of the instances that are created. This would be a huge performance hit though unless you limit the amount of information you are logging.
A better solution would be to use the Trace and Assert capabilities in the System.Diagnostics namespace to selectively trace the program state, or to use a logging facility (log4net, EnterpriseLibrary, NLog, roll your own simple one) to dump thread / stack / variable information as you go.
In any case, adding all this extra information is a big overhead.
EDIT: I got news of this project in my feed: NTrace. It looks like it will fit a little more of what you're trying to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With