Today, while answering few questions on MSDN Newsgroup, I came across one very interesting question and that made me write a brief article about it. The question was "Are there any sort of exceptions that cannot be caught by the runtime?" While answering, I came across another interesting query in which a sender presented a scenario in which he was using a Web Service and at some point the Web Service was raising an exception of type
System.Net.WebException. Although he had placed a proper
Try Catch block, the application was crashing. Interesting huh!!!
These kind of exceptions are usually called FIRST CHANCE EXCEPTIONS.
What is a FIRST CHANCE Exception?
When you debug an application, the debugger gets notified whenever an exception is encountered. At this point, the application is suspended and the debugger decides how to handle the exception. The first pass through this mechanism is called a "first chance" exception. Now depending on the debugger's configuration, it will either resume the application and pass the exception on or it will leave the application suspended and enter debug mode. If the application handles the exception, it continues to run normally.
In Visual Studio, you may see a message in the output window that looks like this:
A first chance exception of type 'System.ApplicationException' occurred in myapp.exe.
If you are using Visual Studio .NET 2003, this message is shown if you have configured the debugger to stop when the specific exception type is thrown.
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. Typically, debuggers are configured to stop on second chance (unhandled) exceptions and allow you to debug.
How to Handle First Chance Exceptions?
If you are Using Visual Studio .NET 2003, you can easily configure how the debugger handles first chance exceptions on a per exception basis or for exception groups.
Let me show you how to enable a specific exception to be caught. I will use
System.Exception in this example.
- Start Visual Studio .NET 2003 IDE and load any project
- Go to Debug menu, select Exceptions
- Expand the Common Language Runtime Exceptions node in the list
Expand the System node
System.Exception in the list
- If you see below in the list, in the area labelled when the exception is thrown, select Break into the debugger
- Click OK
Typically, the default value for "when the exception is thrown" (a.k.a. first chance exceptions) is "Use Parent Settings (the specific exception will inherit the exception group setting.)".
In the same fashion, you can enable a group of exceptions to be caught in a specific manner.
Note: When enabling for exception groups, specific exception settings override the group level setting.