I would like to share one more way to catch unhandled exceptions, without completing the application. This method is incorrect, and it should be used only in the most extreme cases, when no adequate methods help:
1) In the configuration file, we return the CLR mode to the behavior of version 1.0-1.1 :
<runtime> <legacyUnhandledExceptionPolicy enabled="1"/> </runtime>
2) To catch unhandled exceptions, subscribe to the UnhandledException event:
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine((e.ExceptionObject as Exception).Message + " CLR IsTerminating: " + e.IsTerminating); }
3) In the Test class constructor, we expect the threads to finish:
t1.Join(); t2.Join();
All code looks like this:
namespace ConsoleApplication { class Program { static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; var p = new Test(); Console.ReadKey(); } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine((e.ExceptionObject as Exception).Message + " CLR IsTerminating: " + e.IsTerminating); } } class Test { public Test() { var t1 = new Thread(Foo); var t2 = new Thread(Foo); t1.Start(); t2.Start(); t1.Join(); t2.Join(); } public void Foo() { try { throw new OverflowException(); } catch { Console.WriteLine("Специально созданное исключение"); throw; } } } }
ps when launched under the Visual Studio debugger, this method will not work, and the studio will show an exception. When you run the exe itself - there will be no exception.