Handling exceptions
This recipe will describe how to handle exceptions in other threads properly. It is very important to always place a try/catch
block inside the thread because it is not possible to catch an exception outside a thread's code.
Getting ready
To work through this recipe, you will need Visual Studio 2015. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter1\Recipe11
.
How to do it...
To understand the handling of exceptions in other threads, perform the following steps:
- Start Visual Studio 2015. Create a new C# console application project.
- In the
Program.cs
file, add the followingusing
directives:using System; using System.Threading; using static System.Console; using static System.Threading.Thread;
- Add the following code snippet below the
Main
method:static void BadFaultyThread() { WriteLine("Starting a faulty thread..."); Sleep(TimeSpan.FromSeconds(2)); throw new Exception("Boom!"); } static void FaultyThread() { try { WriteLine("Starting a faulty thread..."); Sleep(TimeSpan.FromSeconds(1)); throw new Exception("Boom!"); } catch (Exception ex) { WriteLine($"Exception handled: {ex.Message}"); } }
- Add the following code snippet inside the
Main
method:var t = new Thread(FaultyThread); t.Start(); t.Join(); try { t = new Thread(BadFaultyThread); t.Start(); } catch (Exception ex) { WriteLine("We won't get here!"); }
- Run the program.
How it works...
When the main program starts, it defines two threads that will throw an exception. One of these threads handles an exception, while the other does not. You can see that the second exception is not caught by a try/catch
block around the code that starts the thread. So, if you work with threads directly, the general rule is to not throw an exception from a thread, but to use a try/catch
block inside a thread code instead.
In the older versions of .NET Framework (1.0 and 1.1), this behavior was different and uncaught exceptions did not force an application shutdown. It is possible to use this policy by adding an application configuration file (such as app.config
) that contains the following code snippet:
<configuration> <runtime> <legacyUnhandledExceptionPolicy enabled="1" /> </runtime> </configuration>