Enable first chance exceptions for specific piece of code - c#

I need Visual Studio to throw first chance exceptions only for a specific class.
If i enable First Chance exception in Visual Studio, it enables for the entire solution.My solution is big and I do not want the exceptions to be thrown every where.
I want the exceptions to be thrown by Visual studio only for a specific piece of code/module/method.
How do I do that? Are there any attributes that I can use for this? Or is it possible to enable through code?

As you said >
My solution is big and I do not want the exceptions to be thrown every where.
I want the exceptions to be thrown by Visual studio only for a specific piece of code/module/method.
I will suggest you to use try and catch block for only the piece of code where you want the exception to be thrown by visual studio.
If solution is big, try to open connection only once and at the last point close it.

Related

Why doesn't Visual Studio break on unhandled external exceptions?

I'm using Visual Studio 2017 (15.4.1) while developing an ASP.NET Core MVC 2 application running on .NET Framework 4.6.2.
I'm trying to get Visual Studio to break on all unhandled exceptions that pass through my code. How can I get Visual Studio to break on unhandled exceptions that are thrown in an external library that is called from my code?
These are my settings:
Exception Settings -> Break when thrown:
All defaults. This means:
Don't break when thrown for almost every exception.
Don't continue when unhandled in user code for almost every exception.
Options -> Debugging -> General:
Enable Just My Code
Use the new Exception Helper.
See the following code snippet:
void ThrowExceptionInUserCode()
{
// Exception helper doesn't pop up, and shouldn't.
try { throw new Exception(); }
catch (Exception) { }
// Exception helper pops up, and should.
throw new Exception();
}
void ThrowExceptionInExternalLibrary()
{
// Exception helper doesn't pop up, and shouldn't.
try { PopularLibrary.MethodThatFails(); }
catch (Exception) { }
// Exception helper doesn't pop up, and should.
// This is the thing I'm trying to get to work.
PopularLibrary.MethodThatFails();
}
Note that I cannot disable 'Just My Code', because ASP.NET has a default exception handler, which would make all my exceptions handled.
Edit:
Since my question has been marked duplicate, let me specifiy why its not the same as the other question.
The other question is more general. 'Why does Visual Studio not break at all on an unhandled exception. This works perfectly fine for me. Visual Studio does break on unhandled exceptions. Visual Studio only does not break on unhandled exceptions thrown from an external library, like my code sample specified.
Secondly the original question has many answers, but non answer the original question. (The original asker even mentions this in the replies.)
These other answers solved a different problem for many users, hence the many upvotes.
The problem is that ASP.NET Core catches all exceptions to be able to show an error message to the client rather than crashing the HTTP connection.
So technically all exceptions are "handled" and thus not caught by Visual Studio.
Ideally Visual Studio unhandled exception code would insert itself before the ASP.NET Core exception handler, but so far it doesn't.

Visual Studio 2015+ C#/.NET Debugger: How to break only on unhandld exceptions?

So, I have found a lot of resources and StackOverflow questions on this exact topic, but it seems to only apply to pretty old versions of Visual Studi0 -- like 2012.
My issue is that I want the Debugger to ONLY break when an exception is UN-HANDLED. The official MSDN says that the Debugger breaks on what is called a "first-chance" exception, meaning that it is intended functionality to break even if the exception is going to be handled.
I find it incredibly annoying to have the Debugger break on an InvalidCastException that I have wrapped inside a try-catch. Is there any way that I can force the Debugger to ignore first-chance exceptions that will be handled? A common answer is to just disable breaking on that particular CLR Exception type, but that's honestly a ridiculous solution. I don't want to suppress the Exception everywhere. I just don't want to be notified that an Exception was thrown when I already guarded against it.
I can imagine your frustration, but there has to be something odd with your VisualStudio settings. I can assure you that on my setups, VS never catches exceptions that are handled, and that is/was true across all VS versions ranging from VS2008 upto VS2015.
"FirstChance exception" line you see in the output window is an information that an exception has been just thrown, at exactly that moment, before any handlers were triggered or stacks unwound.
But that does not imply any breaking in VisualStudio. Only a one-liner is written to the debug output, and program continues - stack is unwound, and nearest matching catch is executed, and program runs forward.
Now, the VS/Debugger/CLR can break on exceptions being throw, but it has to be turned on. You can get there by Debug->Windows->Exceptions, or press CTRL+D+E. When you click that, a new panel should appear, with a list of exceptions and one or two options for each of them:
break when thrown
break on unhandled
but that may vary depending on your VS version. For example, in VS Community 2015, there's only "Break when thrown", and "unhandled" is not visible, but still is active for all of them. You just can't turn off breaking on "unhandled".
Anyways, the important thing is that by default, all "unhandled" are selected, and none or almost none of "when thrown" is. In VS2015Community, I see following "when thrown" set by default:
some C++ "Platform::xxxx" exceptions
System.Reflection.MissingMetadata [<-C#]
System.Reflection.MissingRuntimeArtifact [<-C#]
System.Windows.Markup.XamlParseException [<-C#]
Javascript exception: Access Denied, code 0x80070005
some ManagedDebuggingAssistants: LoaderLock, ContextSwitch, ...
a few Win32 exceptions
and that's all. Maybe total of 10..20 very specific types, I didn't count. In "Common Language Runtime" group only three are checked by default, those listed above. No InvalidCastExceptions.
If your VS is triggering at the moment it is thrown, then it means that you, or someone that had access to your VS, has configured it differently. Most probably, in that "ExceptionSettings" panel, you have "InvalidCastException" marked as "break when thrown". Go there, see the state of the checkbox at "InvalidCastExceptions" and uncheck it, and retry.
If this helps for the case of InvalidCastExceptions, and if this problem happens for some other exceptions as well, then you can repeat it for any other type that you dont want to break-on-thrown. And yes, it means that at some point of time you (or someone else) have clicked there and checked them to break on them.
If you have many of them checked to break-on-thrown, then instead of clicking on each one, you can click on the subtree root and check/uncheck whole groups. (btw. maybe you had accidentaly clicked and checked a whole group a week or month ago?)
Also, there's a very useful "Restore Defaults" underrightclick and even a button called "Restore the list to default settings", both of which simply reset everything to the default settings (like in the list I wrote above: some C++, some reflection, some win32, and so on).
Finally, whatever exceptions you deselect for break-on-thrown in ExceptionSettings panel, VisualStudio will still break on any unhandled exceptions. (unless you see there another set of checkboxes, labelled as "unhandled" - there was such thing in i.e. VS2010Pro, but in VS2015Community I dont see it.. maybe it's a Pro thing)
As of Visual Studio 2015, you can go to Debug -> Windows -> Exception Settings. You define which exceptions to automatically break for on a case-by-case basis. There is also a link to this window when VS breaks for an exception - click on "Exception Settings" at the bottom of the window.
On my home computer, I only see one column, "Thrown", so to your point, there is no way to throw only unhandled exception. At work, though, I have a second column called "User Unhandled", which allows me to do exactly what you're talking about. Leaving "user unhandled" checked and unchecking "thrown" causes it to break only on unhandled exceptions, not on ones that are caught. I think this may be a feature of Visual Studio Professional edition - at home I use Community Edition.
If you use the higher VS version like the VS2015, it has no the option to enable/disable the Unhandled Exception like the Old VS version, but it has his own feature:
So if we just want to capture the unhandled exception, we could disable the checkbox.
Is there any way that I can force the Debugger to ignore first-chance exceptions that will be handled?
I don't want to suppress the Exception everywhere. I just don't want to be notified that an Exception was thrown when I already guarded against it.
But if you still want to get the first change exception messages that will be handled, it has no good workaround for this issue, since at this point the debugger does not know if the exception will be caught (handled) by the application, and if you enable the checkbox, it will capture the first-chance exception(When an exception is first thrown in the application, this is classified as a “first chance” exception).
Reference:
https://blogs.msdn.microsoft.com/visualstudioalm/2015/02/23/the-new-exception-settings-window-in-visual-studio-2015/
https://blogs.msdn.microsoft.com/visualstudioalm/2015/01/07/understanding-exceptions-while-debugging-with-visual-studio/#unhandled.
Remember that you can define your own build configuration next to Release or Debug which can follow the #if <name> and #endif marks in your code. There you can for example decide if you want to focus on exception or not depending on configuration.

Visual Studio finish application on Exception

I have some places in the C# application where potential Exception's are not catched, but there is a try-finally block to release resources before crashing in case of an Exception.
When I run the code in Visual Studio and an Exception occurs, it breaks at the corrsponding line, marks it yellow and describes the exception.
That's fine.
But after having noticed and read the exception, I want my application to fail savely (execute the finally blocks). This is exactly what would happen if I ran the code outside Visual Studio. However, when I hit F5 to continue, it gets stuck on that very line, marking it over and over again.
What can I do to tell Visual Studio I want the application to continue = fail?
What's happening is you're seeing the Exception Assistant feature of Visual Studio. Whenever there is an unhandled exception in user code it will display to inform the user of the problem.
Unfortunately in certain circumstances it can't be made to go away and you get the behavior you're describing. It's definitely very frustrating when that happens. The best way to work around it is to disable the exception assistant.
Tools -> Options
Debugging -> Generale
Uncheck "Enable the exception assistant"
Sometimes I find I need to hit F5 several times. I know that it will stop on every rethrow or try-block that the exception goes through, so it may be that it is repeating because the exception is happening in a library function and is filtered through several try statements before leaving the library function. VS, however, will just show that library call several times. I've never gotten truly stuck, though. Hitting F5 a few times will get it moving again.
Visual studio will continue on after breaking on exceptions if you do have a matching catch statement for the type of exception being thrown.
However, you can turn off the exception assistant completely for specific exceptions by going to the Debug > Exceptions menu and unchecking the exceptions you would like to ignore.

How to Debug better even after using try catch

If I use a try/catch and display a messagebox,I can only see the exception but the VS IDE does not point me to the Exact LINE...(although I get the name of the function and stacktrace)
Is there anyway to throw the exception back on the exact line during debugging without removing the try / catch blocks?
Thanks
In Visual Studio, got to the Debug Menu -> Exceptions...
Make sure 'Thrown' is checked as well as 'User-Unhandled'.
That will make Visual Studio break on the line that threw the Exception even if it is handled (thus pointing you to the exact line).
Turn on first-chance exceptions in the debugger exceptions window. This will hook the selected exceptions at the point they are thrown, regardless of whether they are caught or not.
I should warn you that this can be quite tedious if your application triggers a lot of caught exceptions (which reflects a bad design, anyway).
In case you use VS 2017.
Check either Common Language Runtime Exceptions or one you need from the list below.

Continuing in the Visual Studio debugger after an exception occurs

When I debug a C# program and I get an exception throwed (either thrown by code OR thrown by the framework), the IDE stops and get me to the corresponding line in my code.
Everything is fine for now.
I then press "F5" to continue. From this moment, it seams like I'm in an infinite loop. The IDE always get me back to the exception line. I have to Shift + F5 (stop debugging/terminate the program) to get out of his.
I talked with some co-workers here and they told me that this happens sometime to them too.
What's happening?
You probably have the option "Unwind the callstack on unhandled exceptions" checked in Visual Studio. When this option is on Visual Studio will unwind to right before the exception, so hitting F5 will keep ramming into the same exception.
If you uncheck the option Visual Studio will break at the exception, but hitting F5 will proceed past that line.
This option is under menu Tools → Options → Debugging → General.
Update: According to Microsoft, this option was removed from Visual Studio in VS2017, and maybe earlier.
This is because the exception is un-handled and Visual Studio can not move past that line without it being handled in some manner. Simply put, it is by design.
One thing that you can do is drag and drop the execution point (yellow line/arrow) to a previous point in your code and modify the in memory values (using the Visual Studio watch windows) so that they do not cause an exception. Then start stepping through the code again1.
It is a better idea though to stop execution and fix the problem that is causing the exception, or properly handle the exception if the throw is not desired.
1 This can have unintended consequences since you are essentially re-executing some code (not rewinding the execution).
When the IDE breaks on the offending line of code, it stops just before executing the line that generated the exception. If you continue, it will just execute that line again, and get the exception again.
If you want to move past the error to see what would have happened, had the error not occurred, you can drag the yellow-highlighted line (the line that will execute next) down to the next line of code after the offending one. Of course, depending on what the offending line failed to do, your program may now be in a state that causes other errors, in which case you haven't really helped yourself much, and probably should fix your code so that the exception either doesn't occur, or is handled properly.
Once you get an exception Visual Studio (or whatever IDE you might be using) will not let you go any further unless the exception is handled in your code.
This behaviour is by design.
Some said that is by design, but it was never been before. You were able to F5 again and the code would continue until the end or next exception catch.
It was an useful behavior that worked well, and as developers, I think we should not reach artificial barriers while we are debugging and investigating issues in an application.
That said, I found a workaround to this (sort of):
press Ctr+Shift+E (Exception settings)
uncheck the "Common Language Runtime Exceptions" box
press F10 to continue only the exception you are stuck
check "Common Language Runtime Exceptions" again, if you want the breaks to happen again
That seems dirty, too much work for a thing that is used to be simpler, but I guess that is what we have for today.
An uncaught exception will bring down your app. Instead of this, VS will just keep you at the uncaught exception, You will have to terminate or backwind your app.

Categories