Should I just ignore a first chance exception in WCF? - c#

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.

Related

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

Why doesn't Visual Studio 2010 show me a popup and the location where an exception is thrown when my code throws an exception in the debugger?

I remember it used to do this before.
Now it's only a silent print into the output window informing that an exception is thrown.
I know when it can't find the code, it can do this but when I investigate it, the problem code is mine so it should bring me into the offending line immediately at runtime.
Am I missing something?
By default that behaviour only happens if the exception is unhandled. You might have an exception handler somewhere that is quietly handling the exception. Note that certain kinds of projects -- like WinForms, for example -- might insert global exception handlers for you, and possibly those are handling the exception.
In the Debug - Exceptions dialog you can say to break in the debugger when the exception is thrown, regardless of whether it is handled or not.
Look at Debug->Exceptions... dialog. You probably have your exception turned off.
This can happen when developing on a 64 bit OS when the exception occurs in some event, usually in a form's loading event for example.
As others have mentioned, setting exceptions to "Thrown" in the Exceptions dialog is a quick work around, although this will make Visual Studio stop at EVERY exception, even ones you are properly handing in a Try / Catch block.

C#: should all exceptions be caught

Should all exceptions be caught in a C# program, or are some exceptions (such as stack overflow, out of memory etc.) ones that you should allow the program to crash on because there is no way to recover from them?
You should only catch exceptions that you are able to handle. Never ever catch exceptions and do nothing. Do your best to keep the exception from occurring in the first place. This is especially important in .Net because exceptions incur a penalty in performance due to the stack trace.
It depends on the program, of course, but in general, only catch exceptions that you can actually do something about in a meaningful way.
See this question about catching an OutOfMemoryException (you can usually recover from it) and this one about catching a StackOverflowException (generally not possible).
If you're writing a long-running application (e.g. a web server), then of course you'd want to catch all possible exceptions to prevent them from terminating the entire process. If you're writing a low-impact end-user application, then perhaps just logging the exception and failing fast is the best solution.
It's impossible to be (completely) prepared for the unexpected.
Yes, at the very least exceptions should be logged, 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.
From commercial application development POV, all exceptions should be caught and NONE should be allowed to crash the program. Because, now-a-days, computer users can differentiate between an error message and application crash dialog.
A product that crashes gives bad impression to the customer. When you have no way to recover, you can show an error message politely saying that the app will exit now and the user has to start the app again. Then, gracefully exit when the user presses ok on the modal dialog.
Even sometimes you can give useful information when there is no way to recover. For example, in case of out of memory, you can advise the user to close other applications (if any) before starting this app again.
Though, the end result is same, but a friendly error message gives much better impression than an OS generated crash dialog.
MSDN article on the topic:
http://msdn.microsoft.com/en-us/library/ms229005.aspx
Highlights:
Avoid handling errors by catching non-specific exceptions, such as System.Exception, System.SystemException, and so on, in application code. There are cases when handling errors in applications is acceptable, but such cases are rare.
An application should not handle exceptions that can result in an unexpected or exploitable state. If you cannot predict all possible causes of an exception and ensure that malicious code cannot exploit the resulting application state, you should allow the application to terminate instead of handling the exception.
...
You should catch only those exceptions that you can recover from.
...
Do prefer using an empty throw (throw;) when catching and re-throwing an exception. This is the best way to preserve the exception call stack.
MSDN Magazine on Exception Handling changes in .NET 4.0 -
"It's Still Wrong to Use Catch (Exception e)" -
http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070057
When you think that there might be an issue arising from user interaction with your app in an unintended way, then you must always catch a possible exception, and handle it with relevant error messages.

C# create a fatal exception?

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.

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