C# create a fatal exception? - c#

I have a strange scenario when my application can get into an infinite loop when shutting down. It occurs when it wants to do something but the calls fail as it no longer has access (time based). In such a scenario it should just stop.
I record failed attempts and if the count goes above a certain number in a certain time I throw an exception which I expect to start the JIT debugger and stop the application.
I am not entirely sure why it gets into the loop so I want the JIT window that gives me information like the call stack and application status.
I have exception handling, but what I want is to turn it off and somehow generate an exception that will trigger the JIT debugger, however, all other posts I have found have been for handling exceptions and avoid crashes.
If there is another way at runtime to have the application stop and tell me what is happening I would like to know.
Thanks.

You should try Debugger.Launch() and Debugger.Break() methods (but remember that you should use them only in development environment). You can read more here: http://msdn.microsoft.com/en-us/library/7kzs2ysh.aspx

This line:
System.Diagnostics.Debugger.Launch();
will launch the debugger for you. Give it a try.

I have exception handling
Sounds to me that you have too much of it. Only ever catch specific exception types, never catch Exception. Now you can simply throw any other exception type and your app will bomb with an unhandled exception. Which brings up the JIT debugger dialog on your dev machine, a merciful end on your customer's machine.
Using System.Diagnostics.Debugger is good too, but wrap it with #ifdef DEBUG. Your customer doesn't have one.

Related

Should I just ignore a first chance exception in WCF?

Running a WCF service inside Visual Studio, I see a load of exceptions in the Debug output.
A first chance exception of type 'System.ServiceModel.FaultException' occurred in System.ServiceModel.dll
A first chance exception of type 'System.InvalidOperationException' occurred in System.ServiceModel.Channels.dll
They seem to get thrown irregularly: in any case I haven't been able to work out any pattern (i.e. anywhere from every few seconds, to several tens of seconds).
If I set debug to break on FaultException, I see that they are being thrown by System.ServiceModel.Dispatcher.ErrorBehavior.ThrowAndCatch(Exception e, Message message).
The exception message is {"The message with To '' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree."}.
The obvious answer would seem to be "well your address is empty". But this happens before any clients have connected.
Is this just 'normal', or a symptom of something I'm doing wrong?
The quick answer is "yes, you could ignore first chance exceptions". They are exceptions which have actually already been handled. Therefore, they should be considered as a normal execution workflow.
The visual studio notifies the developer for each exception it occurs, even if it is handled. Each exception throws a "first chance exception" which does not interrupt a normal debugging session. If this first chance exception is not handled, then the debugging session gets interrupted by a "second chance exception". The value of the "first chance exceptions" is only for developer's insight knowledge.
In this blog post you can see more details about first chance exceptions. Copying from the referenced post:
Does a first chance exception mean there is a problem in my code?
First chance exception messages most often do not mean there is a problem in the code. For applications / components which handle exceptions gracefully, first chance exception messages let the developer know that an exceptional situation was encountered and was handled.
Hope I helped!
Normally, if you see first chance exceptions in the debug window, but if they do not crash, say, the w3wp.exe process when running without a debugger attached, you can be pretty sure that the framework or the generated classes are catching the exceptions and dealing with them. However, if there are an inordinate amount of such messages or that you suspect that none should be thrown, even if handled, you can use Visual Studio's exception settings to break on handled errors so you can debug/trace.
I agree that all of the first chance exceptions thrown from the framework can be safely ignored, we have found it useful to catch hidden / very hard to replicate bugs on production codebase if an excception gets swallowed (and not 'handled'). Attaching a handler for FirstChance exceptions which logs to a separate log file and is enabled only in a QA environment (these logs are huge) helped us find several bugs in our own codebase. A developer looks at the log file at the end of the day for anything which should not be safely ignored.
While these kind of bugs should have never been in the code in the first place had someone not decided to just swallow an exception, in a messy real world, this is a great tool to continualy improve quality of the codebase.

How to debug code that interacts with low level APIs (like I/O completion ports)?

I wrote a console application that uses Socket's *Async set of methods and it crashes time to time. It doesn't show me where it threw the exception like synchronized code, console just shuts down and I have no idea what have I done wrong.
Is there a way to detect exceptions when it comes to asynchronous operations like this without knowing where to put a try/catch block?
All I need is to know what part of the code makes my application crash.
Edit:
The usual thing with the unhandled exceptions is when you are debugging your code using Visual Studio, it pauses the execution and shows you the line of code that caused the exception (or at least the exception message). But in some situations (e.g. interacting with a low level API like IOCP) your program just crashes and debugging ends with no information about its cause.
What I need is a way to see that particular exception:
"What happened or where (in which method) it happened so my program crashed?"
So I don't ask "What have I done wrong?", I ask "How can I find out what have I done wrong?"
Can I make the execution break at the point where the exception is thrown?
Can I see the call stack after crash to identify the method that caused it?
Could you provide any advice to avoid these kind of situations?
Click Debug-menu -> Exceptions. Make sure Common Language Runtime Exceptions are thrown. Sometimes the IDE unchecks this option. I don't know why, but it's annoying.
Enable System.Net logging to see whats happening underneath

C#: what happens if an exception is not caught

What happens in a C# program if an exception is not caught. Does the program 'crash' with something like a run-time error?
What happens in a C# program if an exception is not caught. Does the program 'crash' with something like a run-time error?
Maybe.
Maybe not.
What happens is implementation-defined.
For example, you might get a dialog box that says "there was an unhandled exception, and I see you have Visual Studio installed. Do you want to start up the debugger and examine the program state?"
You might get a dialog box that says "there was an unhandled exception, do you want to report this to Microsoft?"
If you are already running in the debugger, the debugger probably does something to bring it to your attention.
The runtime is allowed to do whatever it wants, and that includes asking you what to do.
Note that the runtime is aware of whether there's going to be a catch block or not before the finally blocks run. You can easily demonstrate this with a console app. Write an app that crashes, and outputs in the finally block:
Unhandled Exception: System.Exception: Exception of type
'System.Exception' was thrown at
ConsoleApplication1.Program.Main(String[] args)
finally running now
See what happens? The runtime reports the error, gives the debugger a chance to run, or reports the problem to Microsoft, or whatever, before it runs the finally blocks. If they run at all. They might not. Anything can happen. The user could decide to destroy the process, or start a debugger and fix the exception, or whatever.
If you really want to understand how exceptions work in C# you should read this:
http://blogs.msdn.com/b/cbrumme/archive/2003/10/01/51524.aspx
Yes.
Yes.
Something "exceptional" has happened, and your program does not know how to handle it, so it must stop execution at that point and "crash". There will be code that is executed after the crash, such as finally blocks, but basically the party is over for your code.
The best thing to do is to log these events, giving as much intofmation about the state of the system/program at the time of the crash. The Logging Application Block is one of the more robust automatic ways to log errors.
Try it! Depending on the error, it will usually catch. Now, as for should all exceptions be caught, if its something like a[i] where it COULD throw an error if i is too big, but you knew that i was supposed to be kept within bounds (for example, in a for loop), you would not catch that exception.
However, if you are using data coming from a user (say, from a GUI) you would almost always validate it.
Try it yourself!
class Program
{
static void Main(string[] args)
{
int[] arr = new int[1];
arr[5] = 6; //throws an exception; what kind?
}
}
Compile and run this in debug mode for a quick answer to your question.
Or just write some programs. Sooner or later, your code will throw exceptions; it happens to all of us, usually more times than we can count. In console or WinForms applications, an unhandled exception will usually crash the program; in ASP.NET, it will generate an error page, but it won't crash the whole website. You can also write custom code that specifies what to do in case of an unhandled exception, so that your application will fail gracefully.

Finally Block Not Running?

Ok this is kind of a weird issue and I am hoping someone can shed some light. I have the following code:
static void Main(string[] args)
{
try
{
Console.WriteLine("in try");
throw new EncoderFallbackException();
}
catch (Exception)
{
Console.WriteLine("in Catch");
throw new AbandonedMutexException();
}
finally
{
Console.WriteLine("in Finally");
Console.ReadLine();
}
}
NOW when I compile this to target 3.5(2.0 CLR) it will pop up a window saying "XXX has stopped working". If I now click on the Cancel button it will run the finally, AND if I wait until it is done looking and click on the Close Program button it will also run the finally.
Now what is interesting and confusing is IF I do the same thing compiled against 4.0 Clicking on the Cancel button will run the finally block and clicking on the Close Program button will not.
My question is: Why does the finally run on 2.0 and not on 4.0 when hitting the Close Program button? What are the repercussions of this?
EDIT: I am running this from a command prompt in release mode(built in release mode) on windows 7 32 bit. Error Message: First Result below is running on 3.5 hitting close after windows looks for issue, second is when I run it on 4.0 and do the same thing.
I am able to reproduce the behavior now (I didn't get the exact steps from your question when I was reading it the first time).
One difference I can observe is in the way that the .NET runtime handles the unhandled exception. The CLR 2.0 runs a helper called Microsoft .NET Error Reporting Shim (dw20.exe) whereas the CLR 4.0 starts Windows Error Reporting (WerFault.exe).
I assume that the two have different behavior with respect to terminating the crashing process. WerFault.exe obviously kills the .NET process immediately whereas the .NET Error Reporting Shim somehow closes the application so that the finally block still is executed.
Also have a look at the Event Viewer: WerFault logs an application error notifying that the crashed process was terminated:
Application: ConsoleApplication1.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Threading.AbandonedMutexException
Stack:
at Program.Main(System.String[])
dw20.exe however only logs an information item with event id 1001 to the Event Log and does not terminate the process.
Think about how awful that situation is: something unexpected has happened that no one ever wrote code to handle. Is the right thing to do in that situation to run even more code, that was probably also not built to handle this situation? Possibly not. Often the right thing to do here is to not attempt to run the finally blocks because doing so will make a bad situation even worse. You already know the process is going down; put it out of its misery immediately.
In a scenario where an unhandled exception is going to take down the process, anything can happen. It is implementation-defined what happens in this case: whether the error is reported to Windows error reporting, whether a debugger starts up, and so on. The CLR is perfectly within its rights to attempt to run finally blocks, and is also perfectly within its rights to fail fast. In this scenario all bets are off; different implementations can choose to do different things.
All my knowledge on this subject is taken from this article here: http://msdn.microsoft.com/en-us/magazine/cc793966.aspx - please note it is written for .NET 2.0 but I have a feeling it makes sense for what we were experiencing in this case (more than "because it decided to" anyways)
Quick "I dont have time to read that article" answer (although you should, it's a really good one):
The solution to the problem (if you absolutly HAVE to have your finally blocks run) would be to a) put in a global error handler or b) force .NET to always run finally blocks and do things the way it did (arguably the wrong way) in .NET 1.1 - Place the following in your app.config:
<legacyUnhandledExceptionPolicy enabled="1">
The reason for it:
When an exception is thrown in .NET it starts walking back through the stack looking for exception handlers and when it finds one it then does a second walk back through the stack running finally blocks before running the content of the catch. If it does not find a catch then this second walk never happens thus the finally blocks are never run here which is why a global exception handler will always run finally clauses as the CLR will run them when it finds the catch, NOT when it runs it (which I belive means even if you do a catch/throw your finally blocks will still get run).
The reason the app.config fix works is because for .NET 1.0 and 1.1 the CLR had a global catch in it which would swallow Exceptions before they went unmanaged which would, being a catch of course, trigger the finally blocks to run. Of course there is no way the framework can know enough about said Exception to handle it, take for example a stack overflow, so this is probably the wrong way of doing it.
The next bit is where it gets a bit sticky, and I am making assumptions based off of what the article says here.
If you are in .NET 2.0+ without the legacy exception handling on then your Exception would fall out into the Windows exception handling system (SEH) which seems pretty darn similar to the CLR one, in that it walks back through frames until it fails to find a catch and then calls a series of events called the Unhandled Exception Filter (UEF). This is an event you can subscribe to, but it can only have ONE thing subscribed to it at a time, so when something does subscribe Windows hands it the address of the callback that was there before, allowing you to set up a chain of UEF handlers - BUT THEY DON'T HAVE TO HONOR that address, they should call the address themselves, but if one breaks the chain, bap, you get no more error handling. I assume that this is what is happening when you cancel windows error reporting, it breaks the UEF chain which means that the application is shut down immediately and the finally blocks are not run, however if you let it run to the end and close it, it will call the next UEF in the chain. .NET will have registerd one which is what the AppDomain.UnhandledException is called from (thus even this event is not guaranteed) which I assume is also where you get your finally blocks called from - as I can't see how if you never transition back into the CLR a managed finally block can run (the article does not go into this bit.)
I believe this has something to do with changes to how the debugger is attached.
From the .NET Framework 4 Migration Issues document:
You are no longer notified when the debugger fails to start, or when there is no registered debugger that should be started.
What happens is that you choose to start the debugger, but you cancel it. I believe this falls under this category and the application just stops because of this.
Ran this in both release and debug, in both framework 3.5 and 4.0, I see "in Finally" in all instances, yes running it from command line, went as far as closing my vs sessions, maybe it's something on your machine or as Kobi pointed out, maybe platform related (I'm on Win7 x64)

Thrown exception doesnt stop application

Some of exceptions thrown like this:
throw new Exception( errMsg );
... doest reallly stops my application!
My expectation is when I'm throwing any ex. - app shall stop immediately.
But I noticed my app throwing one ex. after another (especially when binding) instead of terminating same time
EDIT_1:
I dont have try-catch block when it can be intercept
EDIT_2:
As mentioned - this mainly happens when binding.
Eg I have object's getter checking user's privileges (GetValue method)- if not raises exception.
I can see in debugger it executing throw new Exception(...) statement but apps doesn't stop.
I've also noticed exceptions are thrown as many times as many items are in bound collection...
Any idea how to force stop binding and rise real exception??
Sample code to illustrate what I'm talkin'
public string Name {
get { return GetValue( name, "Name"); }
}
Uncaught exceptions will cause your application to terminate. Its by design (at least after 2.0 was released; 1.1 had a different behavior, iirc).
They call this "failing fast." The idea is that if an exception you didn't expect (and therefore catch) is thrown, your application is in an unstable state. At this point, its better for it to crash than continue limping along.
Binds behave differently, as all binding operations (in WPF) are designed to catch all exceptions rather than take down your application. Why they made that decision is something that the WPF team would have to tell you.
Exceptions only stop the application if they remain uncaught all the way to the bottom of the current stack. WPF binding is very resilient to most thrown exceptions; instead it will log failures in the output window and carry on. Whether this was a good design decision is a matter for debate...
If I understand you correctly: your app will continue to run if the thrown exception is caught as part of a try/catch block, or if you have set up an exception catch-all handler at the application level.

Categories

Resources