Visual Studio 2010 UnhandledException, ThreadException error handling? - visual-studio-2010

In my code I had an error that was catched by following exceptions while program was running. However when I was running program in Visual Studio when the error was happening application was simply exiting without any error (other errors usually bring me to the problematic line).
if (ApplicationDeployment.IsNetworkDeployed) {
AppDomain.CurrentDomain.UnhandledException += currentDomainUnhandledException;
Application.ThreadException += applicationThreadException;
}
Of course if i remove the if i get this exception handling done by my methods which simply uses MessageBox to show the error. Is there a way to force Visual Studio to catch this error like it catches other types of errors?

Only by using Debug + Exceptions, Thrown checkbox. That makes the debugger stop on the "first chance". At the point the exception is thrown. You typically want to do this:
if (!System.Diagnostics.Debugger.IsAttached) {
// Subscribe the events
//...
}
Note that this already works that way for Application.ThreadException, Winforms already avoids catching exceptions if it sees a debugger. For the exact same reason.

Related

visual studio 2015 c# not break on unhandled exception in formload method [duplicate]

I just came across odd behavior with exception handling in .Net. (I'm using C# in MS Visual Studio 2008, but one question I saw here seemed to imply that what I see is true throughout the .Net world.) I am writing a plain WinForm application. I am intentionally causing an unhandled exception to be thrown inside a form_load event handler, outside of any try block. I get no notification. If an unhandled exception occurs in a normal method, a message pops up telling me that the exception happened, and giving me some information about the problem. But in the handler, the code just quietly exits the function without letting anybody know that it happened. If I add a try/catch block, the exception is caught as expected.
Is it true that this behavior happens in all event handlers? And is this expected behavior? And if so, is it because there is too much danger of bad things happening if an event handler unexpectedly stops?
Whether inside or outside VS, this behavior occurs when there is a debugger attached to the process. However, being a debug version makes no difference. If running outside VS without a debugger attached, the unhandled exception will fire up.
You can check
Why the form load can't catch exception? , and
VS2010 does not show unhandled exception message in a WinForms Application on a 64-bit version of Windows , for possible solutions.
EDIT: This behavior is only specific to the form_load event handler, as far as I know.

Prevent Asp.net MVC WebAPI from stopping (needing to press continue) when exception is caught

I have a try and catch block in a controller in my asp.net MVC webAPI project.
This is the exception that I get if I mess up the date input
An exception of type 'System.ArgumentException' occurred in
mscorlib.dll but was not handled in user code
Additional information: An item with the same key has already been
added.
i tried to add the following
catch (Exception e)
{
output.Add("requestStatus", "fail");
output.Add("errorSumary", "=== Exception in SOAP request ===");
output.Add("errorSuggestion", "effectiveDate was not in the right format or the date already past");
logger.Error("Error: ActivateController - effectiveDate was not in the right format");
}
but when this exception is triggered I still have to press the continue button in visual studio to make this program keep running. Is there any way to make it so the exception doesnt stop the running of the program? (ie so i dont have to click the green Continue button in visual studio)
I know i should try and catch everyType of exception and handle them gracefully I just wanted a built in failsafe that allows it to keep running if one slips under the rug (and I log then using Nlog so you could see if anything is broken via something like splunk).
So it turns out in order to fix this all I had to do was change the following setting in visual studio to be checked when running in debug mode.
The setting is called
break when this exception type is user-unhandled .
I was able to confirm this by switching the Visual Studio release configuration from "debug to Release" where the program would not only catch the exception, but the program would no longer stop its execution thus continuing to catch it time and time again without interrupting the program. I didn't realize the debug configuration by default had the "break when this exception type is user-unhandled" turned on out of the box.
You can see your exception settings in two places I have found. Debug -> Exceptions (and likewise set those back to the defaults if you want to re-enable this behavior).
more information about your debugging settings can be found here
Tools->Options->Debugging

JIT Debugging hiding bug in C# app

I have an application that works fine under visual studio.
However, when I run it stand-alone, a certain operation which throws an exception isn't handled. (The exception is expected, but it's correctly handled under VS.)
I added a line to my machine.config to enable JIT debugging, to try and locate the problem, but I then could not recreate the bug (the exception was handled correctly). Deleting the line causes the bug to come back.
How should I start looking for the cause?
The relevant parts (I believe) of my code (edited to remove extraneous detail) are at http://pastebin.com/i2zLCTn5.
Some suggestions that may affect how your code is behaving in the different environment of Visual Studio:
Stop Visual Studio turning off the JIT Optimizer when you run your program under Visual Studio.There's an option called "Suppress JIT optimization on module load"...you want to try changing that to be NOT ticked.
For more details on what the option does see here:
http://msdn.microsoft.com/en-us/library/ms241594.aspx
Turn off the "hosting process" ...http://msdn.microsoft.com/en-us/library/ms185330(v=vs.80).aspx
Run the Program, then "Attach to Process" (it then won't be in a hosting process, and the modules will have been loaded and JIT optimized).
In the Exceptions dialog tick the "Thrown" check box of the Exception that is being eated/handled....so that you can track down who is handling it and why. You will need to install the NET Framework Sourcecode if the Exception is being handled there so that you can see the details.
You could have a try at running it under WinDBG instead (it may behave differently as you then won't be running under a hosting process i.e. .vshost)....make sure you have the extension DLL PSSCOR4 (if using .NET 4) so that you can make sense of things.
So, I discovered - or rather, a friend explained - the cause of this problem:
You cannot catch exceptions across threads when JIT debugging is disabled, even if execution appears to flow correctly.
The exception was being thrown in a Form.Closing event handler:
form.Closing += new delegate
{
switch(form.DialogResult)
{
case DialogResult.OK:
// do stuff;
break;
case DialogResult.Cancel:
throw new AbortOperationException();
}
}
// ...
try
{
mainForm.Invoke(new Function<Form, DialogResult>(form.ShowDialog), mainWindow);
}
catch (AbortOperationException)
{
// handle abort
}
The solution was to refactor slightly to eliminate the throw:
form.Closing += new delegate
{
if (form.DialogResult == DialogResult.OK)
{
// do stuff
}
}
// ...
var result = (DialogResult)mainForm.Invoke(new Function<Form, DialogResult>
if (result == DialogResult.Cancel)
{
// handle abort
}

vs2010 debugger exception view

My vs2010 shows this message when an exception is thrown:
How can I configure the debugger to show exceptions like this instead:
Thanks!
Big difference between the two. You'll only see the first one when you explicitly configure the debugger to stop when an exception is thrown. You do so with Debug + Exceptions, Thrown checkbox. You don't often use this, really only when your code contains too many catch statements that swallow exceptions inappropriately and making the code misbehave. It also has a knack for showing exceptions in code you didn't write. Click the Break button to allow the debugger to show you the details.
You'll only get the second screenshot when an exception is thrown and there is no catch block to catch it, making it an unhandled exception. That's a fatal error, the program cannot continue. The debugger stops to show you the problem, it is otherwise the end of the debugging session. Without a debugger your program will crash. This is the 'good' kind, you get it by omitting try/catch blocks so your program terminates when something unexpected happens. You will want to write an event handler for the AppDomain.CurrentDomain.UnhandledException event so the user at least has an idea what went wrong. And you for that matter.

Prevent Visual Studio from breaking when throwing exceptions

I test the exceptions interception, so, I don't need that Visual Studio breaks on thinkgs like thrown new NullReferenceException("myVar").
I have the following under Debug=>Exceptions
however, VS breaks on the exceptions. What should I do?
PS.
for the application unhandled exception, I "catch" them using the Application.UnhandledException as in the the following:
''' <summary>Occurs when the application encounters an unhandled exception.</summary> '
Private Sub Application_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
Dim message As String = String.Format("An application UnhandledException were thrown.{1}The application will now terminate.{1}'{0}'{1}{1}StackTrace:{1}{2}", e.Exception.Message, Environment.NewLine, e.Exception.StackTrace)
MessageBox.Show(message)
End Sub
I had same problem when I started using VS2010. I have unit tests, which expect exceptions, and I throw exceptions from my functions. These exceptions are supposed to be handled by the user of my library. In Debug->Exceptions dialog, I unchecked check box under User-Unhandled column for Common Language Runtime Exceptions, and VS stopped breaking on these exceptions. By the way, I don't see second column in the dialog you attached here.
If you throw an exception that is not handled anywhere in your code, Visual Studio is going to break. It doesn't have any other choice: there was an unhandled exception. Outside of Visual Studio, the application would show an error message and inform the user that an unhandled exception occurred.
The options you see in the Debug -> Exceptions dialog only allow you to configure whether Visual Studio breaks on all exceptions, including those that are later handled in your code. These are often referred to as "first-chance" exceptions.
Beyond that, you should never throw a NullReferenceException yourself; this is a runtime exception that is reserved for the runtime framework. Instead, you should throw an ArgumentNullException.
The below method works for me in Visual Studio 2015 (a similar process may work for VS2010).
Taken from the Visual Studio documentation on managing exceptions with the debugger:
In the Exception Settings window, open the context menu by right-clicking in window and then selecting Show Columns. (If you have turned off Just My Code, you will not see this command.)
You should see a second column named Additional Actions. This column displays Continue when unhandled by user code on specific exceptions, meaning that the debugger does not break if that exception is not handled in user code but is handled in external code.
You can change this setting either for a particular exception (select the exception, right-click, and select/deselect Continue when Unhandled in User Code) or for an entire category of exceptions (for example, all the Common Language Runtime exceptions).

Resources