the last exception should be caught by a try-catch block
That will not happen. Except for one case when you run your program with an attached debugger. Thus, you are probably bogged down in the hope that this will work, everyone always starts their program with F5 for a while.
Application.Run () has a breakback in its code that raises events, try / catch-em-all, which raises the Application.ThreadException event when the event handler throws an unhandled exception. This reverse stop is really necessary, especially in the x64 version of Windows 7. Very bad things happen when there is no exception handler. However, when you start the debugger, this reverse does not work, which makes unhandled exceptions too difficult to debug.
So, when you are debugging, your catch clause will be executed. Unhandled exceptions are too difficult to debug. When you run without a debugger, your catch clause will not run, and your program will crash, as you described. Throwing an unhandled exception is too difficult to debug.
So don’t do it like that. How Application.Run () handles unhandled exceptions is configured using the Application.SetUnhandledExceptionMode () method. You will like this version better:
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (!System.Diagnostics.Debugger.IsAttached) { Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); AppDomain.CurrentDomain.UnhandledException += LogException; } Application.Run(new Form1()); } private static void LogException(object sender, UnhandledExceptionEventArgs e) { string errordir = Path.Combine(Application.StartupPath, "errorlog"); string errorlog = Path.Combine(errordir, DateTime.Now.ToString("yyyyMMdd_HHmmss_fff") + ".txt"); if (!Directory.Exists(errordir)) Directory.CreateDirectory(errordir); File.WriteAllText(errorlog, e.ToString()); AppDomain.CurrentDomain.UnhandledException -= LogException; MessageBox.Show("Error details recorded in " + errorlog, "Unexpected error"); Environment.Exit(1); }
With this code, you can easily debug unhandled exceptions. The Debugger.IsAttached test ensures that the debugger always stops when the event handler crashes. Without a debugger, it fires the Application.ThreadException event (which is completely useless) and prefers to listen to all exceptions. Including those that were raised in workflows.
You must warn the user so that the window does not just disappear without a trace. I was going to recommend MessageBox, but noticed that this error is now re-enabled in Windows 10. Sigh.