Created
April 21, 2015 14:25
-
-
Save ioab/3fb442c516492d2a9448 to your computer and use it in GitHub Desktop.
Catching Unhandled Exceptions in WPF Applications
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Windows; | |
| using System.Windows.Threading; | |
| namespace __temp_WPF | |
| { | |
| /// <summary> | |
| /// Interaction logic for MainWindow.xaml | |
| /// </summary> | |
| public partial class MainWindow : Window | |
| { | |
| public MainWindow() | |
| { | |
| InitializeComponent(); | |
| /** | |
| * | |
| * In WPF, Metro, and Windows Form apps, you can subscribe to "global" exception handling events , "respectively": | |
| * | |
| * (1) Application.DispatcherUnhandledException | |
| * (2) Application.ThreadException | |
| * | |
| * These two are only for the UI-thread, main Thread. | |
| * | |
| */ | |
| Application.Current.DispatcherUnhandledException += | |
| (object sender, DispatcherUnhandledExceptionEventArgs e) => | |
| { | |
| MessageBox.Show("A crash occurred, Sorry for the inconvenient. Closing The App."); | |
| e.Handled = true; | |
| App.Current.Shutdown(); | |
| }; | |
| /** | |
| * AppDomai.CurrentThread.UnhandledException fires for any exception on any thread. | |
| * But it fires as the last solution. | |
| * Others may interfene before it | |
| * But since CLR 2.0 , the app will shut down after the handling code is finish. | |
| * To change this behavior, | |
| * add the following to app config file: | |
| * | |
| * <configuration> | |
| * <runtime> | |
| * <legacyUnhandledExceptionPolicy enabled="1" /> | |
| * </runtime> | |
| * </configuration> | |
| * | |
| */ | |
| } | |
| private void Button_Click(object sender, RoutedEventArgs e) | |
| { | |
| throw new Exception("thread exception."); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment