I have a WPF application that consists of multiple projects that have forms, classes, base classes, etc..
Because of the large code base I want to make sure if an exception does happen I can catch it, notify the user and let the application continue without crashing. I understand the pros and cons to doing this.
In the App.xaml.cs of the application I have:
private void OnApplicationStartup(object sender, StartupEventArgs e)
{
Application.Current.DispatcherUnhandledException += CurrentOnDispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
Dispatcher.UnhandledException += DispatcherOnUnhandledException;
UI.Views.Windows.MainWindow.Show();
}
private void DispatcherOnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs dispatcherUnhandledExceptionEventArgs)
{
MessageBox.Show("TEST 3");
}
private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
MessageBox.Show("TEST 2");
}
private void CurrentOnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs dispatcherUnhandledExceptionEventArgs)
{
MessageBox.Show("TEST 1");
}
If an exception happens anywhere those messages boxes are shown which is great, the problem is right after it shows the message the application still crashes. If I run the application in debug, Visual Studio will jump to the place were the exception happened and if I continue it will then go to the message box.
I think the problem has something to do with that but I am not sure. Is there a way to catch the exception like I am above but at the same time not have the application crash after?
Thank You
EDIT
The exceptions that get through to the UnhandledException section will be things like NullReference, NotSupported or Database Exceptions for the most park. If a "serious" exception gets cought like Stack Overflow I will simple notify the user and kill the app. I still need to find a way to stop the app from crashing on non serious exceptions though.
I think you need to set
dispatcherUnhandledExceptionEventArgs.Handled = true;
What kind of exception is your application catching? Using UnhandledException for exceptions that change state will not work unless you are setting HandleProcessCorruptedStateExceptionsAttribute attribute.
From MSDN documentation:
AppDomain.UnhandledException Event
Starting with the .NET Framework 4, this event is not raised for exceptions that corrupt the state of the process, such as stack overflows or access violations, unless the event handler is security-critical and has the HandleProcessCorruptedStateExceptionsAttribute attribute.
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx
I have a SL OOB app (it only runs OOB) and was wondering about the ReportErrorToDOM code in the app.xaml.css:
From what I understand, HtmlPage wont work in OOB as there is no DOM/HTML? Is that why this code is wrapped in a TryCatch block? (this is the default for a new SL4 app).
To get my OOB app to display unhandled errors to the UI, should I judt replace the HTMLPage with a MessageBox.Show?
I can't find anything on Google about this, opinions appreciated...
private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
{
try
{
string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", #"\n");
System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
}
catch (Exception)
{
}
}
As an initial starting position yes you should replace the code with code that uses MessageBox.Show to display the error.
What is appropriate for a production quality release will depend on the type of application. Strictly speaking if your application has encountered an unhandled exception it would be in an indeterminate state so a message box and/or the replacing of the root visual might make sense.
If its a game then simply swallowing the error might even be appropriate or just noting it in some log.
Take a look at the Silverlight Navigation Application template in VS - it uses a ChildWindow to show errors, and this works OOB as well. You could just generate a dummy project from this template and copy/paste most of the code over to your app to get going quickly, then tweak the UI to suit your needs.
I've had a few unexplained crashes happening on both the emulator and the phone itself. Basically when my app crashes I get no dialog box whatsoever and the phone returns to the home screen.
I have the following code to display a MessageBox but this is somehow being bypassed...
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
MessageBox.Show(e.Exception.ToString());
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
MessageBox.Show(e.ExceptionObject.ToString());
}
The thought occurred to me that it might be related to memory, since my app deals with a lot of images. But I figure that would still be caught by my unhandled exception code above. Any ideas on how I should track this down would be appreciated.
Keep an eye on your memory usage. An OutOfMemoryException crashes your app without calling the Application_UnhandledException handler.
You can check the current memory usage with some built in methods. I blogged about this a while ago http://kodierer.blogspot.com/2010/09/windows-phone-memory-constraints.html
Here's the basic code you should add:
var timer = new DispatcherTimer {Interval = TimeSpan.FromSeconds(2)};
timer.Tick += (s, e) =>
{
var memuse = (long)DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage");
var maxmem = (long)DeviceExtendedProperties.GetValue("DeviceTotalMemory");
memuse /= 1024 * 1024;
maxmem /= 1024 * 1024;
MyTextBlock.Text = String.Format("Mem usage: {0} / {1} MB", memuse, maxmem);
};
timer.Start();
A few things which have happened to me:
If you're doing things on other threads, then IIRC exceptions on those threads will cause the app to just terminate. You may want to wrap the new thread code in an exception handler which propagates the exception to the UI thread
If your app throws an exception before the first page is loaded, that can cause the app to just die without the appropriate handler being called
If you've got a StackOverflowException, that can't be caught and will just make the app bomb
You may want to add some debug-build-only persistent logging (loaded and displayed within the app itself) to make it easier to work out how far the previous run of the application had got before crashing.
My app crashed in exactly the same way.
I tracked it down to throwing an OutOfMemoryException inside a DispatcherTimer tick handler, though the problem probably occurs elsewhere as well.
However, it is not the case that an OutOfMemoryException always takes down your program. It does not. I tried it in various other handlers, and it was correctly caught.
I've posted a blog entry about lost exceptions here
Could your app be being watchdoged for being unresponsive for too long? Perhaps due to the load time of lots of images and this code being executed on the UI thread.
Is there any possibility to programatically close Silverlight application on Windows Phone 7?
If you write an XNA Game, you will have access to an explicit Exit() method. If you are writing traditional Silverlight project, then NO, there is no way to programatically close your app. See also Peter Torr's Blog entry on Exiting Silverlight Apps in Windows Phone 7. There he also mentions the option of throwing an unhandled exception, which IMO is a terrible programing style.
An option you may try, is using the WP7 Navigation Service to programatically navigate back out of the application. Not sure if that would work though. Why do you need to Exit?
You can always call an exit by doing this at your landing page use this code on click of your application back button:
if (NavigationService.CanGoBack)
{
while (NavigationService.RemoveBackEntry() != null)
{
NavigationService.RemoveBackEntry();
}
}
This will remove back entries from the stack, and you will press a back button it will close the application without any exception.
Short answer for Silverlight is No.
You should not provide a way to close the applicaiton. Closing the applicaiton should be the users choice and implemented by using the back button the appropriate number of times. This is also a marketplace requirement.
That said, a silverlight application will close if there is an unhandled exception. I have seen a few people try and create programmatic closing by throwing a custom error which is explicitly ignored in error handling. This can work but there is still the marketplace issue.
XNA applications can explictly call Exit().
Some good info here already. Adding to this..
The platform is fully capable of managing closure of apps. The more apps don't provide an exit, the quicker users will become accustomed to not thinking about app house keeping, and let the platform manage it.
The user will just navigate their device using start, back, etc.
If the user wants out of the current app to go do something else quickly - easy - they just hit start.
.Exit(), whilst available for xna, really isn't required anymore either. There was a cert requirement during CTP that games had to provide an exit button. This is now gone.
Non game apps never had the need to implement this.
The more this topic's discussed (and it really has been given a good run around the block), the more the indicators to me suggest there is no need to code an exit.
Update: For those thinking of an unhandled exception as a suitable way of closing an app intentionally or letting the app close due to subpar operating conditions, I would recommend reviewing the comments concerning Application Certification Requirements in this answer. Is there a way to programmatically quit my App? (Windows Phone 7)
Here is another solution.
If you have an error page that i.e. displays error to the end user you can use the
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
base.OnBackKeyPress(e);
e.Cancel = true;
}
And you can instruct user to press start button to exit application.
Add a reference to Microsoft.Xna.Framework.Game, then call:
new Microsoft.Xna.Framework.Game().Exit();
private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
{
while (NavigationService.CanGoBack)
NavigationService.RemoveBackEntry();
}
That works for me fine.
You can close the app using this statement
Application.Current.Terminate();
This worked perfectly on Windows phone 7
System.Reflection.Assembly asmb = System.Reflection.Assembly.Load("Microsoft.Xna.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553");
asmb = System.Reflection.Assembly.Load("Microsoft.Xna.Framework.Game, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553");
Type type = asmb.GetType("Microsoft.Xna.Framework.Game");
object obj = type.GetConstructor(new Type[] { }).Invoke(new object[] { });
type.GetMethod("Exit").Invoke(obj, new object[] { });
Link - source
My 2 pence worth, reasons for an exit
1) there is no interent connection the first time it is run and it needs to create an account on a web service somewhere to run.
2) You need to force an upgrade for the user, again when tied to a web service, you may discover a bug in your app, or have web service changes that mean the user needs to be forced to upgrade, at that point you will want to inform the user that they must upgrade and then exit the app.
Currently in my app I am forced to take the user to a form that says "they" must exit, and if they click back they are again forced back to this page. not very nice.
In Silverlight, I throw an un-handled exception when I have to exit the application. I know that this isn't the graceful method to handle this but it is still the most convenient and easiest solution.
I know that according to the guidelines there shouldn't be any un-handled exceptions in the code but I write why I am explicitly throwing an un-handled exception in the Exception Request document at the time of submission.
Till now this method has always worked and never failed me.
Easiest way to do this is to add a reference to Microsoft.Xna.Framework.Game, then add
using Microsoft.Xna.Framework.GamerServices; before namespace. Then we have a button in our Example.xaml with Click="quit_button". In out Example.xaml.cs we put this code inside our page-class:
private void quit_Click(object sender, EventArgs e)
{
new Microsoft.Xna.Framework.Game().Exit();
//This will close our app
}
var buttonInfo = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.OKCancel);
if (buttonInfo == MessageBoxResult.OK)
{
if (NavigationService.CanGoBack)
{
while (NavigationService.RemoveBackEntry() != null)
{
//
}
}
e.Cancel = false;
}
else
{
//Stop page from navigating
e.Cancel = true;
}
Navigate to App.xaml.cs in your solution explorer and
add a static method to the App class
public static void Exit()
{
App.Current.Terminate();
}
so that you can call it anywhere from your application , as below
App.Exit();
Had a page that was working fine. Only change I made was to add a datagrid to the page (which also added the xmlns) and all of the sudden I'm getting Page Not Found. Checked the UriMappings. Tried the default nav link. No joy.
Ideas?
UPDATE: The answer was that I had a mock class that was not initializing a collection. See Byrant's answer for a way to save yourself some time.
To see what the issue is you need to make one change to your MainPage.xaml.cs:
// If an error occurs during navigation, show an error window
private void ContentFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
Exception ex = e.Exception;
while (ex.InnerException != null)
{
ex = ex.InnerException;
}
e.Handled = true;
ChildWindow errorWin = new ErrorWindow(ex);
errorWin.Show();
}
Once you've made that change when you start the application you should see the exception instead of the page where the exception occurred.
Firebug is always a good friend to see which kind of requests are called ...
Often the devServer is not closed properly , have a look at the taskbar