Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to log or intercept First Chance Exceptions

Tags:

.net

exception

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.

like image 967
Brian Adams Avatar asked Nov 02 '08 05:11

Brian Adams


People also ask

What is a first chance 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.

What is a second chance exception?

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.

What does the FirstChanceException event allow within an ASP NET MVC application?

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.


2 Answers

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.

like image 72
jlnorsworthy Avatar answered Sep 21 '22 12:09

jlnorsworthy


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.

like image 28
Garo Yeriazarian Avatar answered Sep 20 '22 12:09

Garo Yeriazarian