C# Exceptions only caught when debugging? [duplicate] - c#

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Exception handling problem in release mode
I suspect there is a perfectly simple explanation for this, but I can't seem to find it.
When my WinForms C# 4.0 application loads itself in the Program.cs file, the entire Main() function has inside it a try/catch statement.
I have written a little exception wrapper which behaves quite similarly to the vanilla .net "uncaught exception" box, except it provides a bit more information, allows the exception tree to be saved (serialised), and it allows the user to submit the error report directly to me.
Now, it works fine while debugging (F5). If I trigger an exception anywhere in the program which is in the main thread, if there is not try/catch then the exception fires its way all the way back to Main() and shows the custom window.
(All other exceptions I have accounted for and are handled appropriately).
When I run the program simply by running the .exe file, the vanilla .net exception box comes up, not the one I have coded.
Is there any reason you can think of why this would happen?
The strangest thing is that it behaves quite differently when running in debug mode vs running on its own.
I am building as debug - not release.
Edit (22-March-11):
I'm just adding a little addendum here, in case some of you can't find the answer hidden in the comments for the accepted answer below:
Forget that I said I was building as debug instead of release. That is of no relevance - I just added it for extra info. What is important is that when I'm debugging in VS the exceptions are caught as expected, but when executing my EXE outside VS they aren't.
As Cody said, Application.Run() has its own handler for exceptions which is why they never get to my main catch, however I mentioned that I am not even using Application.Run() anywhere in my code... instead my GUI is first launched with Form.ShowDialog().
I have done some experimentation, and can confirm that Form.ShowDialog() behaves the same was as Application.Run() in that exceptions are handled within the method itself.

This is the expected behavior.
The difference you see is a result of the application being run with the debugger attached. When you launch it from within Visual Studio, the debugger is automatically attached (unless, of course, you choose to "Start Without Debugging"). That disables the built-in exception handler, which is the one responsible for showing you the "vanilla" .NET exception dialog. Launching it from outside VS doesn't attach the debugger, leaving the built-in exception handling enabled. (Note that this has nothing to do with compiling your program in "Debug" mode versus "Release" mode.)
See the accepted answer to this related question for more information. I do not believe the difference between VB.NET and C# is relevant in this case.
As that answer mentions, there is a way to disable the built-in exception handler. But before choosing to do so, I recommend reconsidering your approach. Rather than wrapping your entire Main method in a try-catch block, which sounds like a bit of a code smell to me, you might consider handling the built-in AppDomain.UnhandledException event. Jeff Atwood posted a great article here on Code Project about how to replace the standard .NET exception handling with your own more user-friendly method. The solution he proposes has become only that much more elegant as later versions of the .NET FW have improved how the AppDomain.UnhandledException event is handled.

Related

Catching Unknown Exceptions With C#

I have an application (written in C# / ClickOnce) which, for the most part, works fine; it has no memory leaks and runs reliably and is stable for days at a time.
However, it also utilises MEF (so plugins/extensions can be dynamically added to the core assembly). Again, this 'works' currently, but if an exception/fatal error occurs in an externally linked assembly/plugin, it will crash the entire application.
After some recent testing, I found that the application had crashed after around 14 hours of [successful] operation.
With that in mind, my question is really two-fold:
a) is it possible to catch any unhanded exception a plugin (or the main application) may throw, so it can at least output info for debugging assistance?
b) I can't be sure if it was the plugin or the main application which failed. Therefore, I cannot think where to start debugging/tracing the issue. How does one go about finding a bug which only occurs after such a long period of time?
Thanks for any input.
As noted in the comments (I guess I should have read those before I started typing up an answer...)
When an application throws an exception that is unhandled, it fires the UnhandledException event just before death and you can subscribe to that in order to log any details that will help you figure out what happened.
See this SO post for an example on how to use it (includes ThreadException).

What's wrong with the code in MSDN article "How to: Schedule Work on the User Interface (UI) Thread"?

I am trying to launch the code of C# WPF app from online MSDN article: "How to: Schedule Work on the User Interface (UI) Thread" in Visual Studio 2010, Windows XP SP3, .NET4.0
The only differences I've made:
changed the namespace from wpfApplication1 to
WpfApplication1 (since it is in contradiction with article's "1. In
Visual Studio, create a WPF application project and name it."
substituted the line
string[] files = System.IO.Directory.GetFiles(#"C:\Users\Public\Pictures\Sample Pictures\", "*.jpg");
with
string[] files = System.IO.Directory.GetFiles(#"D:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\", "*.jpg");
(according to my Windows XP machine's configuration)
But after pressing the button, the app breaks with exception:
A Task's exception(s) were not observed either by Waiting on the Task
or accessing its Exception property. As a result, the unobserved
exception was rethrown by the finalizer thread
The code compiles without errors but the line:
Matrix m = PresentationSource.FromVisual(Application.Current.MainWindow)
has Intellisense with wavy underline showing the popup warning:
"Possible 'System.NullRederenceException'"
My VS2010 solution (attempting to reproduce this article) can be downloaded from:
http://wikisend.com/download/404394/msdnHow2ScheduleWorkOnTheUI.rar
What's wrong with this code?
And how to correct it?
Update:
The question is not how to observe exception messages but how to launch the MSDN sample code (by a beginner' like me)
I'd prefer asking exception-specific questions separately
Update2:
Errata:
Sorry...
The application doesn't break as I wrote before.
I inserted MessageBox.Show("Finished"); at the end of button1_Click() button click event handler.
Upon first click on the button the MessageBox with "Finished!" shows up.
Upon 2nd click it Messagebox again is shown and but app also throws the mentioned above exception.
And having passed through exception messages and tasks results, I cannot figure out what is wrong!
I'd still like to stress that I am interested in the working sample of article's topic and will post my questions on debugging separately in other question(s)!
Is it reproducible by others?
The problem is that you have an exception that is occurring inside of your task. The message is pretty self-explanatory, but I guess only if you know about exception handling in the TPL. So, to further elaborate on your exact error:
When an exception is thrown from inside of a task, it must be "observed" in 3 different ways:
Check the task's Exception property
Attempt to read the task's Result property (Causing any stored exceptions to be thrown)
Attach an event handler to the TaskScheduler.UnobservedTaskException
If it is not observed in any of the above ways, then the exception will finally be thrown when the garbage collector tries to finalize the task. This is the reason for the exact message you are getting. However, for the deeper, original exception you will need to do one of the 3 above steps and review the actual exception
Here is an MSDN on exception handling in the TPL
Also, as an FYI, it seems that this unobserved exception may not HAVE to be handled, but I havent personally dug in. Even still, it would be better to handle these as you would any code. So, this change should not change how you write your code.

Stackoverflow in InitializeComponent

I have lots of controls (at least hundreds) added to my form, and quite a few of them are custom controls, and the code inside InitializeComponent is huge. Still, I simply cannot see how can there be any recursion and why does the stack overflow happen.
It only happens if I run the Debug version from inside VS (2008, it uses .net framework 3.5 and Winforms). If I just double click on the executable, the application runs.
Can someone tell me how is that possible, and what can I do to find out why?
Thanks.
Possibly the code of your InitializeComponent method contains a lot of local variable / big local variables (e.g struct with a lot of fields) - that use almost all the stack space available, and when running under the debugger within VS there is a little bit less space in the stack, hence the error.
If this is the problem, it might be fixed converting local variables to class fields, and/or splitting the InitInstance method in various methods with their own local variables - that will share the same stack space.
your best bet is to find out exactly where the exception is happening - control Alt E brings up the Exceptions dialog - click under Thrown for common language runtime exceptions and debugging will stop as soon as your error is thrown - from there you can view the call stack and trace the calls to see where you went wrong. (If the shortcut doesn't work, you can click debug/exceptions in visual studio for the same thing)
(Just to be clear - the Exceptions window brings up a dialog with a list down the left, C++ exceptions, Common Language Runtime Exceptions, etc... you want to click the first checkbox in line with the Common Language Runtime Exceptions so that your code breaks as soon as you hit your issue Then for further investiagtion, debug/windows/callstack - or control/alt C - which will quickly let you see if you do have recursion or some other issue.)

Catching an Unhandled Exception Raised by an Unmanaged Sub-Process

Using C#'s System.Diagnostics.Process object, I start an unmanaged exe, that later starts yet another unmanaged exe.
The 2nd exe is causing an unhandled-exception that I'd like my application to ignore, but can't seem to.
I'm using a try/catch statement when I start the first process, but it doesn't seem to catch the exception raised by the 2nd process. When the exception occurs, the just-in-time debugger notifies me and halts my application until I manually click "yes" I want to debug or "no". Then my application proceeds.
The JIT debugger doesn't have source code for the 2ndprocess.exe that is throwing the exception. So, it doesn't tell me what the exception is. I don't really care what the exception is, I just want to know how to catch it and ignore it so my application doesn't get halted by it. By the time the exception occurs, the work is done anyway.
Can anyone offer some insight?
You should be properly handling the exception in the second executable. Your main program won't catch the exception because it isn't throwing one, it is executing something that is.
Edit:
Do you have access to the source of the second process (the one throwing the exception)? Your application shouldn't ever just crash. If the exceptional case gets handled correctly in the second process, you won't have this problem in your primary application.
Edit2:
Since you have access to the source (open source) I recommend you fix the bug. This will help you in two ways:
1) Your program will finally work.
2) You can say you contributed to an open source project.
And, as a special bonus, you get to help out a project you use frequently. Win/Win
Since you are using process.start to actually launch the application, the application creates a separate application domain. Capturing the exception from that application is not something that I believe will be possible, since more than likely the JIT dialog is coming up due to that failed process.
Although not a solution you could stop the dialog if needed, but that has issues of its own.

How to debug random crashes?

we have a dotnet 2.0 desktop winforms app and it seems to randomly crash. no stack trace, vent log, or anything. it just dissapears.
There are a few theories:
machine simply runs out of resources. some people have said you will always get a window handle exception or a gdi exception but others say it might simply cause crashes.
we are using wrappers around non managed code for 2 modules. exceptions inside either of these modules could cause this behavior.
again, this is not reproducible so i wanted to see if there were any suggestions on how to debug better or anything i can put on the machine to "catch" the crash before it happens to help us understand whats going on.
Your best bet is to purchase John Robbins' book "Debugging Microsoft .NET 2.0 Applications". Your question can go WAY deeper than we have room to type here.
Sounds for me like you need to log at first - maybe you can attach with PostSharp a logger to your methods (see Log4PostSharp) . This will certainly slow you down a lot and produce tons of messages. But you should be able to narrow the problematic code down ... Attach there more logs - remove others. Maybe you can stress-test this parts, later. If the suspect parts are small enough you might even do a code review there.
I know, your question was about debugging - but this could be an approach, too.
You could use Process Monitor from SysInternals (now a part of Microsoft) filtered down to just what you want to monitor. This would give you a good place to start. Just start with a tight focus or make sure you have plenty of space for the log file.
I agree with Boydski. But I also offer this suggestion. Take a close look at the threads if you're doing multi-threading. I had an error like this once that took a long long time to figure out and actually ended up with John Robbins on the phone helping out with it. It turned out to be improper exception handling with threads.
Run your app, with pdb files, and attach WinDbg, make run.
Whem crash occur WinDbg stop app.
Execute this command to generate dump file :
.dump /ma c:\myapp.dmp
An auxiliary tool of analysis is ADPlus
Or try this :
Capturing user dumps using Performance alert
How to use ADPlus to troubleshoot "hangs" and "crashes"
Debugging on the Windows Platform
Do you have a try/catch block around the line 'Application.Run' call that starts the GUI thread? If not do add one and put some logging in for any exceptions thrown there.
You can also wrie up the Application.ThreadException event and log that in case that gives you some more hints.
you should use a global exception handler:
http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx
I my past I have this kind of behaviour primarily in relation to COM objects not being released and/or threading issues. Dive into the suggestions that you have gotten here already, but I would also suggest to look into whether you properly release the non-managed objects, so that they do not leak memory.

Categories