Daily Archives: December 27, 2013
Exceptions (part 3, advanced)
For Windows Forms and WPF we have specific exceptions to deal with. Actually these are not really exceptions. They are events, which are raised whenever any unhandled exception occurs. “Unhandled” means there is nothing that catches exceptions and the entire stack did not come up with any solution. Nothing stopped the thread falling down to its lowest level, and even that level does not know what to do with the exception. You can eg. throw an exception on a button click to cause this behavior.
These events allow applications to log information about unhandled exceptions.
In Windows Forms the EventHandler is defined in System.Threading and is called ThreadExceptionEventHandler. If you do not define this event call then your application will crash when unhandled exceptions show up.
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.ThreadException += Application_ThreadException; Application.Run(new Form1()); } // static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { Exception lException = (Exception)e.Exception; MessageBox.Show(lException.Message); } //
The approach in WPF is similar. We are talking in Domains. Therefore we subscribe to AppDomain.CurrentDomain.UnhandledException .
public MainWindow() { InitializeComponent(); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; } // void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Exception lException = (Exception)e.ExceptionObject; MessageBox.Show(lException.Message + "\nIsTerminating: " + e.IsTerminating); } // private void button1_Click(object sender, RoutedEventArgs e) { throw new Exception("user exception thrown"); } //