I recently changed one of the options in the debugger and I think that is what is causing this problem but I can't seem to 'undo' it...I google and all hits come back with the opposite 'why does the debugger not stop on a breakpoint'
anyway can someone shed some light?
EDIT: when I press f5 in debug mode. Everytime. It goes into the Program.cs and stops on
Application.SetCompatibleTextRenderingDefault(false);
in the Main()
Old thread I know, But I just encountered the same problem. All I did was a Delete All Breakpoints (Ctrl+Shift+F9 for me), then a Clean on my startup project, followed by a Rebuild, then Run. After that it stopped breaking where there were no breakpoints.
I just experienced the same problem however mine isn't due to a option change. I think I have found the reason why but no resolution to fix it. I have a Solution with multiple projects, the projects involved are:
Business Logic
Data Access
Console App
In both BL and DA I have a class called Credit.cs. Both classes are in different namespaces.
When I set a breakpoint on line 235 in BL.Credit.cs then the debugger stops on line 236 in DA.Credit.cs even though there are no breakpoints set. I think this is a bug in Visual Studio.
When I remove the breakpoint in BL is subsequently does not stop in the DA either.
I have submitted a bug if you wish to vote https://connect.microsoft.com/VisualStudio/feedback/details/699804/debugger-stops-on-same-line-in-different-class-where-there-is-no-breakpoint
Here's a workaround for the behavior of breakpoints activating in each class that has the same name even if fully-qualified names are different. After you set a breakpoint, go to the Breakpoints window (Debug | Windows | Breakpoints if it isn't already up). Right-click the breakpoint that's firing in too many same-named classes (e.g. Project2.Action breaks when you only wanted Project1.Action to have a breakpoint) and selection "Condition." Set the condition value to something like this: this.GetType().FullName == "Project1.Action".
Thereafter, the condition makes it so that execution only breaks on the class with the correct fully-qualified name.
Does it stop by giving you an exception or does it just completely stop the execution of your application? If you don't have the UnHandledExceptionHandler in your code it can look like it just stops but you actually have an exception.
UPDATE:
Here is what your Main method should look like to capture unhandled exceptions as try/catch don't always work.
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
throw new NotImplementedException();
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// You should/MAY see an error right here.
throw new NotImplementedException();
}
Related
I had an app that worked well in Debug. Then I switched to Release and built the solution. I got a prompt asking for things like "continue to debug" etc, and chose the one that deactivate "Just My Code" (note: I'm new in this).
I launched my .exe and my app gave me an exception in a place my code worked just fine these past 2 weeks.
The code in question:
private void DgDeliveryOrders_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (string piece in e.AddedItems)
{
Database.Pieces.Add(piece);
}
foreach (string piece in e.RemovedItems)
{
Database.Pieces.Remove(piece);
}
FillDetailsDataGrid();
}
Database.Pieces is a model property in my library project:
public static class Database
{
public static List<string> Pieces { get; set; }
}
I chose the static route because I used it in several places and it was easier (I don't know if it's the best practice, but it worked in Debug).
But then, each time I clicked on a item in my DataGrid, I got an exception: Object reference not set to an instance of an object. Plus something telling me things about optimized code.
I switched back to Debug, it worked, no more errors. I switched again to Release, the same error is back. Breakpoints were acting funny (sometimes it stopped, sometimes not), and although I had the exception message, my ex was null.
After following some topics here, I checked that my solution was in Release for my 2 projets. I deactivated "Optimize" in the projets properties too. What did it change? Breakpoints not working at all.
So I checked again "Optimize", reactivated Just my Code and... my code isn't working in Debug anymore. Nor do the breakpoints.
I tried to reboot Visual Studio, but nothing changed.
At this point, I don't know what to do, it's the first time I do a release, what did I do wrong?
Thank you for reading.
UPDATE
The code problem was resolved in the comments, as for the VS problem, it solved itself after several reboot of the software/computer.
In LINQPad, Debug.Assert() and Trace.Assert() from the System.Diagnostics namespace don't work as expected.
Instead of breaking - i.e. popping up a message box or whatever else happens to be configured for <trace> - they simply print "Fail:" or "Fehler:" to the output window and let the program continue on its merry way. In other words, instead of a noisy, unignorable explosion there are only near invisible micro-farts that intersperse "Fail:" into the textual output.
Is there any way of getting Assert() to revert to the default behaviour under LINQPad?
Alternatively, is there a simple way of mocking a Trace.Assert() so that failure results in a noisy explosion (i.e. exception, message box, whatever) and the source of the failure is pinpointed in the form of a line number or similar?
My unit tests are based on Trace.Assert(), which makes them totally useless if the function cannot break the program at the point of failure.
In Visual Studio everything works normally but not in LINQPad. I haven't fiddled with any system-wide settings but I did install Mono at some point in time. I went through all settings in LINQPad with a fine comb but to no avail. The LINQPad version is 4.57.02 (non-free), running on Windows 7 Pro (German) and Windows 8.1 Pro (English).
I googled high and wide but the only thing I could find is the topic Trace.Assert not breaking, neither showing the message box here on Stack Overflow. Its title certainly looks promising but the answers therein don't.
P.S.: I tried mocking by adding
class Trace
{
public static void Assert (bool condition)
{
if (!condition)
throw new Exception("FAIL!");
}
}
to the LINQ script and setting a breakpoint on the throw statement. Clicking on the relevant call stack entry in LINQPad's debugger takes me to the relevant source line, so this sort of works. However, I couldn't find an equivalent to FoxPro's SET DEBUG ON for invoking the debugger directly from the source code instead of having to set a breakpoint on the throw...
To answer the second half of your question, i.e., how do you get the LINQPad debugger to break when an exception is thrown, the answer is to click either of the 'Bug' icons on the toolbar.
Click Break when exception is unhandled (red bug) to make your query break whenever an unhandled exception is thrown.
Click Break when exception is thrown (blue bug) to make your query break whenever an exception is thrown, whether or not it is handled.
You can get LINQPad to make either setting the default by right-clicking and choosing Set as default. (Doing so forces the debugger to always attach to your queries, which incurs a small performance cost.)
As to why Debug.Assert(false) doesn't display a dialog, this is because this behavior hasn't been implemented in LINQPad. You could implement this easily as an extension, by adding the following code to My Extensions:
public class NoisyTracer : TextWriterTraceListener
{
public static void Install()
{
Trace.Listeners.Clear();
Trace.Listeners.Add (new NoisyTracer (Console.Out));
}
public NoisyTracer (TextWriter writer) : base (writer) { }
public override void Fail (string message, string detailMessage)
{
base.Fail (message, detailMessage);
throw new Exception ("Trace failure: " + message);
}
}
Then, to enable, write your query as follows:
NoisyTracer.Install();
Debug.Assert (false);
When I create a new project, I get a strange behavior for unhandled exceptions. This is how I can reproduce the problem:
1) create a new Windows Forms Application (C#, .NET Framework 4, VS2010)
2) add the following code to the Form1_Load handler:
int vara = 5, varb = 0;
int varc = vara / varb;
int vard = 7;
I would expect that VS breaks and shows an unhandled exception message at the second line. However, what happens is that the third line is just skipped without any message and the application keeps running.
I don't have this problem with my existing C# projects. So I guess that my new projects are created with some strange default settings.
Does anyone have an idea what's wrong with my project???
I tried checking the boxes in Debug->Exceptions. But then executions breaks even if I handle the exception in a try-catch block; which is also not what I want. If I remember correctly, there was a column called "unhandled exceptions" or something like this in this dialog box, which would do excatly what I want. But in my projects there is only one column ("Thrown").
This is a nasty problem induced by the wow64 emulation layer that allows 32-bit code to run on the 64-bit version of Windows 7. It swallows exceptions in the code that runs in response to a notification generated by the 64-bit window manager, like the Load event. Preventing the debugger from seeing it and stepping in. This problem is hard to fix, the Windows and DevDiv groups at Microsoft are pointing fingers back and forth. DevDiv can't do anything about it, Windows thinks it is the correct and documented behavior, mysterious as that sounds.
It is certainly documented but just about nobody understands the consequences or thinks it is reasonable behavior. Especially not when the window procedure is hidden from view of course, like it is in any project that uses wrapper classes to hide the window plumbing. Like any Winforms, WPF or MFC app. Underlying issue is Microsoft could not figure out how to flow exceptions from 32-bit code back to the 64-bit code that triggered the notification back to 32-bit code that tries to handle or debug the exception.
It is only a problem with a debugger attached, your code will bomb as usual without one.
Project > Properties > Build tab > Platform target = AnyCPU and untick Prefer 32-bit. Your app will now run as a 64-bit process, eliminating the wow64 failure mode. Some consequences, it disables Edit + Continue for VS versions prior to VS2013 and might not always be possible when you have a dependency on 32-bit code.
Other possible workarounds:
Debug > Exceptions > tick the Thrown box for CLR exceptions to force the debugger to stop at the line of code that throws the exception.
Write try/catch in the Load event handler and failfast in the catch block.
Use Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException) in the Main() method so that the exception trap in the message loop isn't disabled in debug mode. This however makes all unhandled exceptions hard to debug, the ThreadException event is pretty useless.
Consider if your code really belongs in the Load event handler. It is very rare to need it, it is however very popular in VB.NET and a swan song because it is the default event and a double-click trivially adds the event handler. You only ever really need Load when you are interested in the actual window size after user preferences and autoscaling is applied. Everything else belongs in the constructor.
Update to Windows 8 or later, they have this wow64 problem solved.
In my experience, I only see this issue when I'm running with a debugger attached. The application behaves the same when run standalone: the exception is not swallowed.
With the introduction of KB976038, you can make this work as you'd expect again. I never installed the hotfix, so I'm assuming it came as part of Win7 SP1.
This was mentioned in this post:
The case of the disappearing OnLoad exception – user-mode callback exceptions in x64
Here's some code that will enable the hotfix:
public static class Kernel32
{
public const uint PROCESS_CALLBACK_FILTER_ENABLED = 0x1;
[DllImport("Kernel32.dll")]
public static extern bool SetProcessUserModeExceptionPolicy(UInt32 dwFlags);
[DllImport("Kernel32.dll")]
public static extern bool GetProcessUserModeExceptionPolicy(out UInt32 lpFlags);
public static void DisableUMCallbackFilter() {
uint flags;
GetProcessUserModeExceptionPolicy(out flags);
flags &= ~PROCESS_CALLBACK_FILTER_ENABLED;
SetProcessUserModeExceptionPolicy(flags);
}
}
Call it at the beginning of your application:
[STAThread]
static void Main()
{
Kernel32.DisableUMCallbackFilter();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
I've confirmed (with the the simple example shown below) that this works, just as you'd expect.
protected override void OnLoad(EventArgs e) {
throw new Exception("BOOM"); // This will now get caught.
}
So, what I don't understand, is why it was previously impossible for the debugger to handle crossing kernel-mode stack frames, but with this hotfix, they somehow figured it out.
As Hans mentions, compile the application and run the exe without a debugger attached.
For me the problem was changing a Class property name that a BindingSource control was bound to. Running without the IDE I was able to see the error:
Cannot bind to the property or column SendWithoutProofReading on the
DataSource. Parameter name: dataMember
Fixing the BindingSource control to bind to the updated property name resolved the problem:
I'm using WPF and ran into this same problem. I had tried Hans 1-3 suggestions already, but didn't like them because studio wouldn't stop at where the error was (so I couldn't view my variables and see what was the problem).
So I tried Hans' 4th suggestion. I was suprised at how much of my code could be moved to the MainWindow constructor without any issue. Not sure why I got in the habit of putting so much logic in the Load event, but apparently much of it can be done in the ctor.
However, this had the same problem as 1-3. Errors that occur during the ctor for WPF get wrapped into a generic Xaml exception. (an inner exception has the real error, but again I wanted studio to just break at the actual trouble spot).
What ended up working for me was to create a thread, sleep 50ms, dispatch back to main thread and do what I need...
void Window_Loaded(object sender, RoutedEventArgs e)
{
new Thread(() =>
{
Thread.Sleep(50);
CrossThread(() => { OnWindowLoaded(); });
}).Start();
}
void CrossThread(Action a)
{
this.Dispatcher.BeginInvoke(a);
}
void OnWindowLoaded()
{
...do my thing...
This way studio would break right where an uncaught exception occurs.
A simple work-around could be if you can move your init code to another event like as Form_Shown which called later than Form_Load, and use a flag to run startup code at first form shown:
bool firstLoad = true; //flag to detect first form_shown
private void Form1_Load(object sender, EventArgs e)
{
//firstLoad = true;
//dowork(); //not execute initialization code here (postpone it to form_shown)
}
private void Form1_Shown(object sender, EventArgs e)
{
if (firstLoad) //simulate Form-Load
{
firstLoad = false;
dowork();
}
}
void dowork()
{
var f = File.OpenRead(#"D:\NoSuchFile756.123"); //this cause an exception!
}
Consider this simple console application:
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
throw new Exception();
}
}
}
I run this under the debugger in either Visual Studio 2010 or Visual Studio 2012 Beta.
When I do so, naturally the debugger stops at the exception. Ok so far.
But when I press F5 to continue (or choose Debug|Continue) it stops at the same exception again.
I have to stop debugging for the program to exit. I expected the program to exit when I pressed F5.
Does anyone know why it behaves the way that it does?
[EDIT]
I've marked a reply as an answer, but to see a weird consequence of the debugger's behaviour, consider the following code:
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
throw new Exception();
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine("Unhandled Exception.");
}
}
}
Run this under the debugger and press F5 a load of times, then look at the output. You'll see a lot of "Unhandled Exception" messages, despite the code only actually throwing it once. The debugger is causing the exception to be thrown multiple times! This is what I find strange.
What did you expect?
Consider the following method:
private void Test()
{
throw new Exception();
int u = 4;
}
When the exception is thrown, the debugger allows you to navigate to the calling context to see if your program catches the exception. If it's not the case, it never exits the Test method by skipping the exception, that's why int u = 4; is unreachable.
In your example, it's the same:
private static void Main(string[] args)
{
throw new Exception();
// If I'm here, I will exit the application !
// But this place is unreachable
}
You can't exit the Main method scope because of your exception. That's why you can't exit your application while debugging using F5.
If you have no debugger attached, your application will of course crash because of an unhandled exception, but this is another story.
It doesn't do that. If the application wasn't running in the debugger, you'd get an "application quit unexpectedly" dialog - but not in Visual Studio.
While I'm not exactly sure why it behaves like that, it may be because it gives you the option to move the "currently executing line" arrow (the yellow array) to the next line that should be executed and to resume operation.
Otherwise, yes, you need to stop the application explicitly.
The VS2012 debugger won't continue past an unhandled exception
By default, the debugger stops on all exceptions, that are not caught (i.e. unhandled) - this can be changed in the Exceptions dialog (CTRL+ALT+E, with my keybindings)
Consider the following simple application: a windows form created by a "new C# windows application" sequence in VS that was modified in a following way:
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(new Form1());
}
catch (Exception ex)
{
MessageBox.Show("An unexpected exception was caught.");
}
}
Form1.cs contains the following modifications:
private void Form1_Load(object sender, EventArgs e)
{
throw new Exception("Error");
}
If I press F5 in IDE, then, as I expect, I see a message box saying that exception was caught and the application quits.
If I go to Debug(or Release)/bin and launch the executable, I see the standard "Unhandled exception" window, meaning that my exception handler doesn't work.
Obviously, that has something to do with exception being thrown from a different thread that Application.Run is called from. But the question remains - why the behavior differs depending on whether the application has been run from IDE or from command line?
What is the best practice to ensure that no exceptions remain unhandled in the application?
Normally Application.ThreadException will handle the exception in the Load event. You'll get the ThreadExceptionDialog that offers the Quit and Continue options.
But not when a debugger is attached. The catch clause in the message loop that displays the dialog is intentionally disabled in that case. That's necessary because it would be very difficult to trouble-shoot exceptions if that dialog pops up when you debug a program. Which this catcher no longer active, your catch clause in the Main() method now gets a shot at the exception.
You can make it consistent by using Application.SetUnhandledExceptionMode() in the Main() method. You shouldn't, exceptions really are hard to debug if you do this. If you want to customize exception handling for the UI thread then you should register your own Application.ThreadException handler:
if (!System.Diagnostics.Debugger.IsAttached)
Application.ThreadException += myThreadException;
Trapping unhandled exceptions in worker threads requires a AppDomain.UnhandledException handler. They are not recoverable.
Also beware of a bug in 64-bit Windows, exceptions in the Load event are swallowed without diagnostic when a debugger is attached. Force AnyCPU mode to avoid that trap.
In addition to catching any exceptions thrown inside the Main method you must also handle AppDomain.CurrentDomain.UnhandledException and Application.ThreadException.
Not sure why the behavior differs with and without a debugger attached though.