Standard way to do exception handling in Silverlight/Windows Phone - c#

I want to know if there is a standard way to do some error handling in Windows Phone silverlight application.
What I mean by error handling is something like
Displaying a dialog windows when data connection lost or any exception in windows phone application.
Proper way to do logging in run time.
I did some research on this but did not find anything useful, any code example or reference link is welcomed.
Thank you

There seems to be to parts to this question. How to display error messages and how to handle exceptions
Exceptions
A pattern I've seen used frequently in many environments and lagugages (not just Silverlight or .NET) is to have a top-level exception handler that handles uncaught exceptions. From here, how you handle the error is up to you. It could be logged to a database, file or discarded.
Handling Errors
In my opinion, the best way is to design the software so that there is a minimum of potential errors and prevent them from occurring in the first place. For instance, if the connection is lost, instead of displaying an error message disable parts of the UI that require a connection and provide some indication to the user is that the app is now in a disconnected.

Related

Exception control when release an application?

Possibly an obvious question to some but couldn't find a duplicate.
I'm packaging the final version of a Windows Forms solution I've been working on and am getting it ready for online distribution. What are the best practices when doing so? We've already had some trouble with packaging the installation file and have run into hurdles to test the program on different PCs, both 32 and 64-bit included.
More specifically, should "throw;" commands be commented out or left in the final release? Would this expose any of the inner workings of the solution itself?
Released application should not crash when exception occurs. You will want to inform the user, something went wrong and log your exception, but you do not want to crash! Informing user should be done in a friendly manner and not just by putting exception.ToString() into the message box.
It is a good practice to add Application.ThreadException or AppDomain.CurrentDomain.UnhandledException handlers to handle all exceptions in your Application. How exactly to do that, is answered in the following thread: Catch Application Exceptions in a Windows Forms Application
However, make sure that your application survives in a usable state, i.e. handle exceptions in a proper way for your application.
I usually add a preprocessor directive for handling exceptions on the application level, since I want them to trow while debugging. For example:
#if !DEBUG
Application.ThreadException += new ThreadExceptionEventHandler(MyHandler);
#endif
It should also be mentioned, that if you have code pieces where you anticipate that Exception might occur, such as network communication error, you should handle those pieces explicitly. What I am saying is, we should not completely forget about exception handling, just because we configured an unhandled exception handler on the application level.
Keep all of your exception handling intact.
Add an event to the starting form in the application, attaching to the Application.UnhandledException event. This will fire if an exception propogates up the stack.
This is the point to inform the user that the application has crashed. Log the error here and then abort gracefully.
Your point about revealing internals, thats up to you to decide. You can obfuscate the source code if you wish, but if you are releasing in Release build mode, and you are not providing the .PDB, then this is the first step.
Ultimately, the DLL / EXE can be decompiled anyway, so its up to you. Debug mode will reveal a lot more than Release mode, but not much more.
Ideally, you should be catching anything that's thrown higher with throw;. Carefully check your code and try to ensure that thrown exceptions are dealt with appropriately. Unhandled exceptions are logged - you can see this information in the Windows Event Viewer. Depending on what details you put in them, unhandled exceptions could give clues as to the inner workings of your application. However, I would suggest that unhandled exceptions are a poor source of information, and that anyone who wanted to know how your application worked could simply disassemble it, unless you've obfuscated it.
Some exceptions cannot be caught by surrounding code with try/catch blocks, so your application should also implement an unhandled exception handler. This gives you the opportunity to show the user an error message and do something with the exception - log it, send it to support, discard it, etc.

Your application has stopped working, even when hooking to UnhandledExceptionHandler

I have added a global error handler at the AppDomain level to my C# application, by hooking into the UnhandledExceptionHandler event.
My problem is, that even though i am handling this exception, i still get the popup saying "App has stopped working".
Is this normal behaviour? Can it be turned off? or maybe it is good practice to actually have this message displayed?
Is this normal behaviour?
Yes. Think about it, where should your code be resumed? In what state?
Can it be turned off?
Only by handling exceptions a the appropriate point in your program, ie in the toplevel code. The UnhandledExceptionHandler is not a replacement but a diagnosis-tool for incomplete handling.
or maybe it is good practice to actually have this message displayed?
Yes. You should log exceptions that arrive there but you've already lost control.
I don't think is possible to recover the existing instance of an app when you get at that point. MSDN has no information about it and is suggested " If sufficient information about the state of the application is available, other actions may be undertaken — such as saving program data for later recovery." (link)
It kind of makes sense to not be able to recover. If you catch an exception in the Unhandled ExceptionHandler it means that your application was not able to deal with it so is your last chance to log what happened (for later investigations) or save the user's data. It sounds like an architecture problem if the "unhandled" exception handler must "handle" exceptions and recover the app.
Why not recover by creating a new instance of the app? (or by using the Restart and Recovery feature)

Catching all exceptions in c#

I'm developing a GUI app in C#.
It's a multithread app, and I would like to wrap all the threads (some of them I don't open, e.g. NetClient.StartDownload which is a none blocking function) with a try/catch statement so that if an exception is thrown and uncaught, I could log it and report to base.
I tried using Application.ThreadException and AppDomain.CurrentDomain.UnhandledException, but they seem to only catch GUI exceptions.
Is there a different way I need to handle this?
The code in each thread would need to have a try-catch. Exceptions are not marshalled across threads... and an unhandled exception just brings the application down.
To catch all Exceptions - just use the base Exception type.
catch(Exception e) { // log e }
Updated:
You could take a look at AppDomain.UnhandledException - handle this event for logging unhandled exceptions on any thread ; however you can't stop the application from going down. For more check out
http://www.albahari.com/threading/#_Introduction - towards the end of that page.
The best answer is: don't. There's already a system for doing this built right into the operating system.
If you let the exceptions "bubble up" and out of the program, modern OS'es include Windows Error Reporting, which will give the user the option of sending an error report to Microsoft. (Note: do not send error reports automatically - think long and hard about the legal ramifications regarding privacy laws...)
The error report includes not just the exception information and full stack trace, but also includes a good portion of your process' memory, as well as exactly which OS modules were loaded (so you can even tell whether the client had a relevant Windows Update patch applied). It wraps up all of this information into a minidump file (and also includes a few XML files with additional info).
This error report is uploaded to Microsoft's servers, so you don't have to worry about setting up and maintaining a "call home" server. All error reports for your programs are categorized using advanced heuristics into "buckets", with each "bucket" containing reports that are likely to be caused by the same bug.
Microsoft exposes all of this information to you (as the software publisher) through a site called Winqual. Using Winqual, you can examine all of the error reports, and use their heuristical bucketizing algorithms to decide which bugs are most impacting your customers. You can also download each individual report for more detailed investigation.
If you have a symbol server and source control server set up in your organization (and you certainly should), then you can just load the minidump from a downloaded error report right into Visual Studio, and it will automagically check the old source out of source control and allow you to inspect the exact state of the program at the moment it crashed.
Finding and fixing bugs has never been this easy.
To summarize, here's what you need to do:
Set up a symbol server and a source server in your organization. Establish a release policy to ensure that all releases get source-indexed pdbs added to the symbol server before they get released to the customer.
Establish an account with Winqual. You'll need an Authenticode code-signing certificate; if you get a non-VeriSign code-signing cert, then you'll also have to spend $100 for an "organizational certificate" from VeriSign.
Modify your release policy to include creating mapping files for your releases. These mapping files are uploaded to Winqual before shipping the release.
Do not catch unexpected exceptions. If you do ever need to catch them, be sure to rethrow using throw and not throw ex, so the stack trace and original program state is preserved.
For more information, I can highly recommend Debugging .NET 2.0 Applications by John Robbins. In spite of the "2.0" in the title, this book is still completely relevant today (except that the only source server example is using Visual SourceSafe, which was a complete joke even back then). Another good book if you need to do a lot of debugging is Advanced .NET Debugging, though it is starting to show its age, especially since the new VS2010 debugging advancements make a lot of its techniques out of date.
We need to catch exceptions at the smallest possible unit. As mentioned by Gishu, Exceptions which occur in the threads do not get propgated back to the main thread in many cases.
I had blogged about a similar experience some time back at WCF service unhandled exception error

Long running App, how handle Errors?

i have to implement a Info Terminal. I choose dot.net and the terminal is only a touchpad.
So this System running 7 days 24 hours.
So i call a Webservice, display Data, show Website stuff. Many things can going wrong.
Have you some recommendations for this scenario?
Every function in an try catch? AppDomain.CurrentDomain.UnhandledException event?
Thanks Andreas
Basically, you should handle any error as soon as it is possible - so if you're calling webservice wrap all the calls in a try/catch block and handle the error there - you can, for example, log the exact error, aggregate many webservice-related exception in more generic, DataSourceFaultException (name is only for example), which will be then received by UI and UI will be able to easily determine, that it can't display requested info because communication failed, and choose to retry, notify user or do anything else.
However - with long running application there are many more errors you'll have to deal with. Many of them are not easy to predict, as they're not necessarily related to any specific call - you can run out of memory, a recursion might cause stack overflow, a system timer can reach it's max value and start from the beginning etc.
You shouldn't handle those errors in every method, as it will only hurt code readibility and will be error prone. Those errors are best handled by UnhandledException event. However, you must remember, that when the exception reaches UnhandledException event, you cannot assume anything about state of your application - the error might have corrupted some (or even all) of internal state. So when such condition occurs, it's best to try to create an error log and gracefuly restart the application (not necessarily whole application - maybe it will be possible to reinitialize application's state - if so, that's a valid option too. However, you must be aware that you won't be able to recover from some errors and handle such situation anyway).
It depends.
If you can handle appropriately an exception within a function - handle it. If not - create a global exception handler to inform user or log it.

Handling rude application aborts in .NET

I know I'm opening myself to a royal flaming by even asking this, but I thought I would see if StackOverflow has any solutions to a problem that I'm having...
I have a C# application that is failing at a client site in a way that I am unable to reproduce locally. Unfortunately, it is very difficult (impossible) for me to get any information that at all helps in isolating the source of the problem.
I have in place a rather extensive error monitoring framework which is watching for unhandled exceptions in all the usual places:
Backstop exception handler in threads I control
Application.ThreadException for WinForms exceptions
AppDomain.CurrentDomain.UnhandledException
Which logs detailed information in a place where I have access to them.
This has been very useful in the past to identify issues in production code, but has not been giving me any information at about the current series of issues.
My best guess is that the core issue is one of the "rude" exception types (thread abort, out of memory, stack overflow, access violation, etc.) that are escalating to a rude shutdown that are ripping down the process before I have a chance to see what is going on.
Is there anything that I can be doing to snapshot information as my process is crashing that would be useful? Ideally, I would be able to write out my custom log format, but I would be happy if I could have a reliable way of ensuring that a crash dump is written somewhere.
I was hoping that I could implement class deriving from CriticalFinalizerObject and have it spit a last-chance error log out when it is disposing, but that doesn't seem to be triggered in the StackOverflow scenario which I tested.
I am unable to use Windows Error Reporting and friends due to the lack of a code signing certificate.
I'm not trying to "recover" from arbitrary exceptions, I'm just trying to make a note of what went wrong on the way down.
Any ideas?
You could try creating a minidump file. This is a C++ API, but it should be possible to write a small C++ program that starts your application keeps a handle to the process, waits on the process handle, and then uses the process handle to create a minidump when the application dies.
If you have done what you claim:
Try-Catch on the Application.Run
Unhandled Domain Exceptions
Unhandled Thread Exceptions
Try Catch handlers in all threads
Then you would have caught the exception except perhaps if it is being thrown by a third party or COM component.
You certainly haven't given enough information.
What events does the client say leads up to the exception?
What COM or third party components do you use? (Do you properly instance and reference these components? Do you pass valid arguments to COM function calls?)
Do you make use of any un-managed - un-safe code?
Are you positive that you have all throw-capable calls covered with try-catch?
I'm just saying that no-one can offer you any helpful advice unless you post a heck of lot more information and even at that we probably can only speculate as to the source of you problem.
Have a set of fresh eyes look at your code.
Some errors cannot be caught by logging.
See this similar question for more details:
StackOverflowException in .NET
Here's a link explaining asynchronous exceptions (and why you can't recover from them):
http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=c1898a31-a0aa-40af-871c-7847d98f1641

Categories