JIT Debugging hiding bug in C# app - debugging

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
}

Related

Visual Studio Debug Mode, Allow Exception to Kill the Program

I have a piece of code in C# that's essentially like the following...
WriteFile();
try {
RunTest();
} finally {
DeleteFile();
}
Now this has been planned so that even on failure, it cleans up the files it left behind. This works when not run in debug mode (although it pops up a message asking if I want to debug the program or close it. Closing it produces the appropriate results).
When I run this in debug mode and hit an exception inside of RunTest, I only seem to have two options. In the first one, I tell debugging to stop. This is equivalent to killing the program and the block in finally does not run (so the file doesn't get deleted like it should). If I tell it to continue, it doesn't propogate the exception up and instead, it just hits an exception somewhere else.
Is there anyway to get debug mode to continue like a normal program after hitting an exception?
From the Debug menu, choose Exceptions (or use Ctrl + Alt + E). This will bring up a dialog where you can uncheck appropriate checkboxes in the "User-unhandled" column for exceptions which you don't want to stop at while debugging.
I believe that will make exception propagation work normally. And you can still set a breakpoint either in the try or finally block to see what's happening.
Check Debug/Exceptions if there are any exceptions set.
Another option would be to handle the event Application.ThreadException (Windows Forms) or Application.UnhandledException (Silverlight etc.) and tell the application to continue or exit, depending on the severity of your exception.

Visual Studio 2010 UnhandledException, ThreadException error handling?

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.

Visual Studio 2008/2010 SP1, how to jump back out of a catch?

I am using the debugger (vs2008).
Once I've stepped into a catch statement, I would like to know if there is any way to set the execution cursor back to the beginning of the try.
Just dragging it there doesn't seem to work, is there some setting I need to change?
Example:
try
{
//Want the cursor back here
}
catch
{
//some code, cursor is here...
}
Apparently it depends which flavor of .NET runtime you are using. At the time I first wrote this, it worked fine for me when I tried it, but I was using my work PC, with a 32-bit OS installed.
I'm using this code snippet to test:
try
{
throw new Exception();
}
catch
{
Console.WriteLine("Error"); // Breakpoint here
}
You can't set the cursor on the try line. It will be on the line following immediately after it (the opening of the block statement).
Dragging the cursor to that line or the try line works fine for me when I compile my .NET program for x86. It will also work if you're running a 32-bit OS. However, when you're on a 64-bit environment and compile for Any CPU or x64, you will get the following error message:
Since this is for debugging purposes only, a possible workaround for you would be to compile for x86, so the 32-bit runtime will be used. Go to the Build menu and choose Configuration Manager. Under Platform, select x86 or New... if it's not currently in the list. In the latter case, you'll get a new dialog. Pick the options as shown below and click OK:
If I right click and do "set next statement" then I get the following error dialog:
Unable to set the next statement to this location. The attempt to unwind the callstack failed.
Unwinding is not possible in the following scenarios:
Debugging was started via Just-In-Time debugging.
An unwind is in progress.
A System.StackOverflowException or System.Threading.ThreadAbortException exception has been thrown.
By elimination the reason why you cant move the cursor (The same as setting the next statement) must be #2.

How to detect an unmanaged app has aborted

I have a C# app which invokes an unmanaged C++ application via Process.Start()
On some machines, if this C++ app aborts, I'm left with the Just-In-Time error dialog showing
Is there a way from C# to detect that the C++ app has errored and just restart it
(I don't have the source to and therefore can't modify the C++ app)
The JIT debugger dialog is showing because the C++ app crashed in some way. Whilst the dialog is open, the process is still present (but suspended) which means that the Process class wont consider it to have "exited" until the JIT dialogue is dismissed or an attached debugger ends the process.
You could either disable JIT debugging on the machines experiencing the problem (I think that disabling the Machine Debug Manager service may disable JIT debugging), allowing the app to crash and die (and, therefore, report as "exited"), or (and I've no idea how you would go about doing this) see if you can make your host C# app attach itself as a debugger for the C++ app and receive notification of the crash from the C++ app, terminate it, and then act upon the information it has ended.
If the C++ is a console based you can check two things,
The exitcode, commonly 0 means closed normally otherwise is problem (but I Think this depends on the convention used to develop this applications)
Check the standard Error if it is empty, so everything is ok
using(Process p = new Process())
{
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = "any.exe";
p.Start();
string error = p.StandardError.ReadToEnd();
p.WaitForExit()
if(error.Length == 0 && p.ExitCode == 0)
{
}
}

How to temporarily deactivate all try / catch blocks?

Is there a possibility to deactivate / activate all try catch blocks in the whole project as easy as clicking a button?
I need this for debugging when I don't want the catch block to handle the exception, but instead prefer that VS breaks into the code as if the try catch block was not there.
At the moment I am commenting out the try/catch blocks but this is inefficient.
Environment: VS 2008 with C# as language.
To catch exceptions the moment they're thrown ("first-chance exceptions" in Win32 parlance):
in VS2008: go to Debug, Exceptions...
by VS2015: this has been moved to Debug > Windows > Exception Settings
Then check the box Thrown for Common Language Runtime Exceptions.
There is no way to deactivate try/catch blocks.
However, for debug purposes, if you want to break as soon as a particular type of exception is thrown, you can get Visual Studio to do that (Debug -> Exceptions; select the exception type you're interested in and check the "Thrown" box).
Thought about this today and found an other solution. The advantage of this is that the IDE will stop at the exact point of the occuring exception.
Somewhere globaly defined:
Namespace Global.System
Public Class NeverOccurException
Inherits Exception
End Class
End Namespace
At the beginning of each source code file:
#If DEBUG
Imports CatchAtReleaseException = System.NeverOccurException
#Else
Imports CatchAtReleaseException = System.Exception
#End If
Usage:
'Compiled in DEBUG-Mode the TryCatch is "disabled", because the
'the ALIAS CatchAtReleaseException is set to "NeverOccurException"
'Compiled as RELEASE the TryCatch is "enabled", because the ALIAS
'is set to the regular "System.Exception"
Public Sub SampleSub()
Try
'...
Catch ex As CatchAtReleaseException
End Try
End Sub
Have fun with it,
Greetings,
Ted
If you want to do in the IDE, Debug -> Exceptions is the dialog where you can ask the IDE to break when a specific/category/all exceptions are thrown.
You can change the way Visual Studio breaks when an exception occurs. By default, it breaks on unhandled exceptions. If you go to menu Debug > Exceptions, you can uncheck Common Language Runtime Exceptions and make other changes in the IDE's behavior when exceptions occur. For example, you can have it break on only one kind of exception; there's a long list there.
I have done this on rare occasions when trying to debug.

Resources