简体   繁体   中英

How to catch exceptions for objects defined in XAML in WPF

Is there a way to catch Exceptions from Objects declared in XAML such as a StoryBoard and keep the application from crashing completely?

In this particular case users will rarely encounter an exception relating to an un-animatable or unaccessible property path. I am working to address these issues but in general the app is critical and I would like to prevent it from simply crashing in these instances.

The app is a UserControl that is Hosted in a windows forms app via ElementHost.

How do you handle these types of exceptions and keep the app running?

Some additional info I tried using something like:

Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;    

as a means of catching the exceptions but Application.Current is always null so I can't use it.

In a nutshell I need to ensure that no matter what happens the app itself continues to run.

Oh the horror when you get xaml related crash errors! :) I don't have the full receipt in my head here right now, and I need more information about your issue, but make sure to hook on to all following error handlers(App.xaml.cs in WPF, check link below for forms).

DispatcherUnhandledException += UnhandledDispatcherException;
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

private void UnhandledDispatcherException(Object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        // do your stuff here!
        e.Handled = true; // Ex is now handled and will not crash your app
    }

This one is forms only I think(dont have my devbox here).

Application.ThreadException += UnhandledThreadException

Add your handlers and log/System.Diagnostics.Trace.WriteLine/breakpoint away!

Check this example from MSDN regarding AppDomain. Verify that AppDomain.Current is not null when starting as well.

Snippet:

public class Example 
{
   [SecurityPermission(SecurityAction.Demand,Flags=SecurityPermissionFlag.ControlAppDomain)]
   public static void Main()
   {
     AppDomain currentDomain = AppDomain.CurrentDomain;
     currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
   ...
   }
}

You may also do this after your InitializeComponents, if Application.Current is null.

if (System.Windows.Application.Current == null)
    new System.Windows.Application();

And ofc check your debug output! :)

Hope it helps,

Cheers

Stian

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM