Catch unhandled exceptions from editor - c#

We are using MEF within our WPF application (MVVM) to embedd external editors. At some point in our main view there is a content element where the editor is going to be placed in.
Now we would like to catch any unhandled exception from that editor and then reload the editor. The only thing I have found is to use DispatcherUnhandledException from the Application class. From there I would have to somehow reach the main view editor and tell it to reload the crashed editor.
I was wondering if there is a "lower" level point, where I could catch the exception? Does anyone have some experience with it and could help he out here?
Thanks

So my answer would be: you better don't if you even could. When you get an unhandled exception, your app is no longer in a stable state. Where exactly would you resume to? What if your external editor throws a Corrupted State Exception (e.g. a Win32 SEH exception) like an AccessViolationException or OutOfMemoryException? Your whole app might be in an undetermined state at that point, so further execution might lead to data loss and/or damage. Furthermore, the CLR might not guarantee that your app can continue:
SEH exceptions are a different class from those exceptions raised by
your program. A program might raise an exception because it tried to
pop an item from an empty stack or tried to open a file that didn't
exist. All of these exceptions make sense in the context of your
program's execution. SEH exceptions refer to a context outside of your
program. Unlike program errors, an SEH exception indicates that the
integrity of the runtime's process may have been compromised.
Please read about SEH and CLR exceptions here.
Here is what I'm not suggesting you to do, but rather for your information: you could prevent your app from closing after catching an unhandled exception by updating your app.config file:
<runtime>
<!-- the following setting prevents the host from closing when an unhandled exception is thrown -->
<legacyUnhandledExceptionPolicy enabled="1" />
</runtime>
But, as Microsoft states, if you ignore exceptions, the application may leak resources and abandon locks.

Related

Is there any way to print any extended information on StackOverflowException?

One of my clients reported that the software I develop terminates unexpectedly. In app log, the only text available is Process is terminated due to StackOverflowException. There is no more information which would help me diagnose and fix it.
Is there any way to get the location where the exception was thrown? VS breaks on StackOverflowException, but is there any feasible method of diagnosing it without running the application in the debugger (or looking for it in all methods which contain recursion)?
You cannot normally execute any code after a stack overflow, it's one of the rare uncatchable fatal exceptions, so you cannot simply catch it to log any extended details.
The only way you could work around that is by tracking the exceptions from outside of the code that has a stack overflow. You would need to create a native code application to hosts the CLR. If you do that, you can specify that StackOverflowException is not 100% fatal. This is briefly mentioned on the StackOverflowException MSDN page:
If your app hosts the common language runtime (CLR), it can specify that the CLR should unload the application domain where the stack overflow exception occurs and let the corresponding process continue. For more information, see ICLRPolicyManager Interface.
But even that would still mean that a simple try...catch is not sufficient to actually catch the exception. You would have to make sure that the exception handling is not done from the app domain that has a stack overflow. It might be done from a different app domain, or it might be done from unmanaged code.

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#: 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.

Wouldn’t handling an exception be a better idea

1)
1 - Only handle exceptions that you
can actually do something about, and
2 - You can't do anything about the vast majority of exceptions
a) I assume that “By not handling an exception” the text is suggesting that we should let the exception bubble up the stack, where runtime will abort our application?!
b) But why is letting the runtime abort the exception preferred over catching an exception, logging it and then informing the user of failure? Only difference between the two is that in the latter case application isn’t aborted
For example, if database goes down, why should the whole program crash ( due to not handling an exception ), if we can instead catch the exception, log it and notify user of failure and that way we can keep the program up and running
2) If you know that exception potentially raised by some block of code can’t be handled, should you include this code inside a try-finally block or is it better to leave it outside any try-finally blocks?
Thank you
No, the guideline is not to catch an exception you cannot do anything about except at the top-level of your application or thread.
You should try to avoid letting your application crash - log the information somewhere, give a message to your user explaining what happened, and tell them how to report the error to you. Perhaps also try to save their unsaved data in a recovery file so that the next time the application starts it can offer the option to attempt to recover their lost work.
Try looking at it this way... The database goes down. How do you know? Because you get an timeout/an exception/something. But your application probably isnt getting the exception. ADO.NET/Linq to SQL/Entity Framework/Whatever data provider you are using is actually getting the exception and throwing it to your application. To me, this is what that advice is advising: as a component designer, prefer to throw exceptions you can't do anything about.
For the database down example, is there anything the ADO.NET data provider can do? Can it bring a server back up? Repair network connections? Reset permissions? No. So it doesn't handle the exception, it throws it.
The guideline you cite is for component development, not the outer edge of a run-time boundary (a thread or application). At that level, it would be correct to make a decision on how to handle exception that have bubbled that far.
I think the person you are quoting suggests that you should let the exception bubble up the stack until something higher up can make sense of it or until it reaches the top of the call stack where you do have code that would log it, or display a error message to the user then exit your program if it is fatal, or carry on if it is not.
Sometimes it may be better to not continue executing the program - if you get a OutOfMemoryException for example or some other situation where the programs actions are undefined - a potential disaster.
I think the key to
Only handle exceptions that you can actually do something about
is that you should only handle the exception if you can carry on from that point in your application.
To take a trivial example.
If you're looking for a file on the user's system and it's not there when it should be you should raise the "file not found" exception. Now if you can recover from this (say by simply recreating the file) then do so and carry on. However, if the file can't be recreated then you shouldn't let your program carry on.
However, this doesn't mean you can't have a top level catch all exception handler in your main program to display a friendly message to the user, perhaps to log the exception or even mail it to you the developer.
That statement holds true. But it is a reference to catching exception in the deeper layers of application. Basically most of the code we write does not need exception handling. It is only the client part of the application is responsible for catching the error and presenting it to the user - as well as logging.
For example, the same business code/database code can be used in a web application and windows/wpf application and logging/handling could be different and deeper layers do not know about how this will be handled so they need to leave the responsibility to the UI tier.
The point is that you don't want to have try/catch blocks nested everywhere in your code as this tends to hide issues with your code. It is better to only implement exception handling where you understand the error and the desired outcome, else don't handle it and let it bubble up.
As for as the errors bubbling up, you should have a global exception handler for these uncaught application errors. This is only implemented in one spot in your app and will allow you to log or present the error to the user. Again this is only implemented in one spot in your app, and is implemented by hooking the application.error event.
Event to hook in .net win forms application:
AppDomain.CurrentDomain.UnhandledException
Event to hook in .net asp.net application:
HttpApplication.Error
Enjoy!
Without knowledge about the context of both statements, stated that both statements apply to methods and classes then they make sense:
A piece of code which calls a method can only handle exceptions for which it has enough information about the context. In most cases a piece of code won't have enough information, to handle all exceptions.
Example: A piece of code, which calls a method SaveData() can handle a DatabaseStorageException when it knows, that it saves data to a database. On the other hand, if the piece of code is programmed in a storage agnostic manner, than catching such a specific exception is not a very good idea. In this case it is better to let the exception pop up the callstack and let some other code handle the exception, which has enough context information to handle it.

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