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.
Related
I've got a C# Windows Forms application that (outside of debug mode) works perfectly. When I run it in debug mode, each action I take has a random chance of crashing the application (like clicking a button, or closing the main form). There is a lot of async code running in the background, but the app crashes even when no tasks seem to be running (the _formClosing method is an entirely Synchronous method). Notably, the first thing most button clicks in my app do is change the visibile and enabled properties of some buttons, and then will start writing messages to the log - the app crashes before any logs get written (using NLog)
The error being thrown is:
System.Runtime.InteropServices.SEHException
HResult=0x80004005
Message=External component has thrown an exception.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
With output
An unhandled exception of type 'System.Runtime.InteropServices.SEHException' occurred in mscorlib.dll
and trying to resume the application just ends the debugging session.
The fact that it's not any one specific section of code or event that's triggering the crash, and that the code never crashes outside of debug mode leads me to believe this might be a Visual Studio issue. Are there any settings I can configure within Visual studio to make this crash less prone to occurring? or if not, is there any way to get more information than 'cannot Evaluate the stackTrace'?
Other Information that may or may not be relevant, the memory and CPU usage are both very low at the time of crashing (40MB or so and about 5% CPU utilisation). I'm running the latest Visual Studio Community 2019. The app runs on .Net Framework 4.8. My OS is a local VM running windows 10 enterprise. I also don't think I'm running any Trusteer applications.
My code is also all heavily Try Catched, especially around the button clicks.
Thanks for any help, let me know if I'm missing any relevant information
Edit: I've discovered the line that's causing the issue, commenting out this line causes the app to run fine, completely error free
var ignore = currentJob.jobConfig.ToObject(t); //jobConfig is a JObject
The cast works fine, but by doing the cast, somehow the exception mentioned above and shown below is triggered
Edit #2: Repairing, updating and reinstalling visual studios has not changed the issue, the app still seems to work fine 10-40% of the time, and crash the rest of the time
I found a solution to my problem, by adding 'return;' statements everywhere and removing them one by one (removing large sections of my code). I eventually found the line that was causing problems. It turns out, if you serialise and then deserialise a CancellationToken, visual studio's debug session becomes prone to randomly crashing when, presumably, it tries to do a certain operation on the object you have deserialised to. The solution was just to make the cancellation token either private, or add [JsonIgnore]
Code to reproduce the problem: (run the void method, and then try closing the window)
private void BreakVS()
{
ClassWithCancellationToken someClass = new ClassWithCancellationToken();
someClass.ts = new CancellationToken();
var json = JsonConvert.SerializeObject(someClass);
JObject jObject = JObject.Parse(json);
var test = jObject.ToObject(typeof(ClassWithCancellationToken));
}
public class ClassWithCancellationToken
{
public CancellationToken ts; //change to private to
}
The answer to my original question then, is to start with Jeroan's solution to try debugging on a different device, if the code still breaks on said device then try what worked for me (hack and slash your code until you find what's breaking it) - or a more sophisticated approach to debugging your code more thoroughly. If your code works on another device, then try Micheal's approach to update/repair/reinstall your Visual studios install
Of course, the one thing I still don't know how to do, is to locate the faulty code without spending an hour removing sections of my code until I find the cause.
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.
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.
The following bit of code catches the EOS Exception
using (var reader = new BinaryReader(httpRequestBodyStream)) {
try {
while (true) {
bodyByteList.Add(reader.ReadByte());
}
} catch (EndOfStreamException) { }
}
So why do I still receive first-chance exceptions in my console?
A first chance exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll
Is there a way to hide these first chance exception messages?
To avoid seeing the messages, right-click on the output window and uncheck "Exception Messages".
However, seeing them happen might be nice, if you're interested in knowing when exceptions are thrown without setting breakpoints and reconfiguring the debugger.
The point of "first-chance" exceptions is that you're seeing them pre-handler so that you can stop on them during debugging at the point of throwing. A "second-chance" exception is one that has no appropriate handler. Sometimes you want to catch "first-chance" exceptions because it's important to see what's happening when it's being thrown, even if someone is catching it.
There's nothing to be concerned with. This is normal behavior.
In Visual Studio you can change the settings for the way the Debugger handles (breaks on) exceptions.
Go to Debug > Exceptions. (Note this may not be in your menu depending on your Visual Studio Environment setting. If not just add it to your menu using the Customize menu.)
There you are presented with a dialog of exceptions and when to break on them.
In the line "Common Language Runtime Exceptions" you can deselect thrown (which should then stop bothering you about first-chance exceptions) and you can also deselect User-unhandeled (which I would not recommend) if want to.
The message you are getting should not be in the console, but should be appearing in the 'Output' window of Visual Studio. If the latter is the case, then I have not found a possibility to remove that, but it doesn't appear if you run the app without Visual Studio.
Unlike Java, .NET exceptions are fairly expensive in terms of processing power, and handled exceptions should be avoided in the normal and successful execution path.
Not only will you avoid clutter in the console window, but your performance will improve, and it will make performance counters like .NET CLR Exceptions more meaningful.
In this example you would use
while (reader.PeekChar() != -1)
{
bodyByteList.Add(reader.ReadByte());
}
I had this problem and couldn't figure out where the exception was thrown. So my solution was to enable Visual Studio to stop executing on this kind of exception.
Navigate to "Debug/Exceptions"
Expand the "Common Language Runtime Exceptions" tree.
Expand the "System" branch.
Scroll down to where "NullReferenceException" is, and check the
"throw" checkbox, and uncheck the "user-handled".
Debug your project.
If you want more control over these messages, you can add a handler:
Friend Sub AddTheHandler()
AddHandler AppDomain.CurrentDomain.FirstChanceException, AddressOf FirstChanceExceptionHandler
End Sub
<Conditional("DEBUG")>
Friend Sub FirstChanceExceptionHandler( source As Object, e As Runtime.ExceptionServices.FirstChanceExceptionEventArgs)
' Process first chance exception
End Sub
This allows you to silence them as mentioned in other comments, but still makes sure you are able to be aware of them. I find it is good to see how many I am really throwing if I log a message and timestamp to a text file.
Actually if are having many exceptions per second, you would achieve must better performance by checking reader.EndOfStream-value.. Printing out those exception messages is unbelievably slow, and hiding them in visual studio won't speed up anything.
in VB.NET:
<DebuggerHidden()> _
Public Function Write(ByVal Text As String) As Boolean
...
I think the stream is throwing this exception, so your try is scoped to narrow to catch it.
Add a few more try catch combos around the different scopes until you catch it where its actually being thrown, but it appears to be happening either at our outside of your using, since the stream object is not created in the using's scope.
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.