Exception handling made easy in XAML Applications.

Gone are the days when you need to write try/catch blocks for every piece of logical code and show it in a message box. New projects use the centralized error handling concept. Likewise, in web apps, as we use Global.ASAX Application_Onerror Event, in WPF apps, we can also write the exception handling at one single place.

However, you would still continue to write Try/Catch Blocks around your logical piece of code, to catch specific exceptions such as File IO, Cast Exceptions

In Xaml, we can hook an event to the entire application that would be triggered when an error occurs in the application.

We could do this in the Overriden OnStartup event in the App.xaml.cs

An excerpt is show below

        /// <summary>
        /// Raises the <see cref="E:System.Windows.Application.Startup"/> event.
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs"/> that contains the event data.</param>
        protected override void OnStartup(StartupEventArgs e)
        {
            Application.Current.DispatcherUnhandledException    += new DispatcherUnhandledExceptionEventHandler(AppDispatcherUnhandledException);

            base.OnStartup(e);
       }    
        

         /// <summary>
        /// The dispatcher unhandled exception.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Threading.DispatcherUnhandledExceptionEventArgs"/> instance containing the event data.</param>
        void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            HandleException(e.Exception);

            e.Handled = true;

        }


        /// <summary>
        /// Handles the exception.
        /// </summary>
        /// <param name="ex">The ex.</param>
        private static void HandleException(Exception ex)
        {
            LogException(ex);
        }



        /// <summary>
        /// Log the exception.
        /// </summary>
        /// <param name="ex">The ex.</param>
        private static void LogException(Exception ex)
        {
            if (ex == null)
                 return;

            ExceptionPolicy.HandleException(ex, "Default Policy");
        }


The above LogException uses Enterprise Libary Exception Policy to handle the errors. You could replace it with your own.

However, please note that if you are using BackGroundWorker, you need to write code explicitly to handle the error occured on the background thread.
A sample BackGround Worker error handling excerpt is as show below.

    /// <summary>
        /// Invoke the Time-Consuming task on a background worker
        /// so that the screen is responsive in the mean time.
        /// </summary>
        private void PerformActualWork()
        {
            BackgroundWorker backGroundWorker = new BackgroundWorker();
            backGroundWorker.DoWork += new DoWorkEventHandler(ActualBackgroundWorker_DoWork);
            backGroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ActualBackgroundWorker_RunWorkerCompleted);
            backGroundWorker.RunWorkerAsync();
        }


       /// <summary>
        /// Perform tasks in the boackgroud.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ActualBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //Do work here.
            e.Result = App.Dowork();
        
        }


     /// <summary>
        /// Execute when the background jobs are complete.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ActualDataBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
         {
             bool result = false;

             //Check for errors when calling doWork service.
            if (e.Error != null)
            {
                 //Handle errors on Background Worker explicitly here.
        HandleErrors(e);
                  return;
            }
            else
            {
                 if (e.Result != null)
                    result = (bool)e.Result;
            }
    }

Cheers,
Diablo iii
By [)ia6l0 iii   Popularity  (3624 Views)