1. Introduction
When we work with the Task class or async methods (async/await), we can catch exceptions the usual way — with a try-catch around an await or using ContinueWith. Exceptions don't "get lost"; they are returned to the calling thread.
But if we create a thread via Thread, things get trickier. Each thread has its own entry point (ThreadStart) and execution context. If an unhandled exception occurs inside the thread, it won't "return" to the main thread — it will be thrown only in that thread.
- In .NET Framework: an unhandled exception in one thread terminates the whole application.
- In .NET (Core/5+): only that thread will terminate, the app continues running (which can lead to hidden bugs).
Bottom line: if you don't catch exceptions inside a thread, you'll most likely just not see them. So proper error handling in threads is a must.
Fun fact: exceptions that escape from a Thread are like an elusive ninja: they disappear, and later you scratch your head wondering why the logic didn't run.
2. How do exceptions work inside a thread?
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread thread = new Thread(DoWork);
thread.Start();
// Let's wait for the thread to finish so we can see what happens
thread.Join();
Console.WriteLine("Main finished normally");
}
static void DoWork()
{
Console.WriteLine("Working in a separate thread...");
throw new Exception("Trouble! An error occurred in the thread.");
}
}
Depending on the platform (old .NET Framework or modern .NET Core/5/6/7/8/9), the behavior will differ: either the whole application will crash or only the thread. But the main point — the exception won't arrive in the main thread, and you can't handle it from the outside.
Important! Trying to wrap thread.Join() in a try-catch won't help catch an exception from another thread — it "lives" and "dies" inside that thread.
3. How should you catch exceptions in Thread?
Only inside the thread — in the function you pass to the Thread constructor. Wrap anything that can throw in a try-catch.
static void DoWork()
{
try
{
Console.WriteLine("Working...");
throw new Exception("Something went wrong again!");
}
catch (Exception ex)
{
Console.WriteLine($"[Thread] Caught exception: {ex.Message}");
// Here you can log, send to UI/server, etc.
}
}
Exception handling in threads is the thread code's responsibility. You can't expect the calling code to automatically catch the error.
4. How to know in the main thread that something went wrong in another thread?
In real apps it's important to deliver the error information to the main thread.
- Use thread-safe mechanisms like ConcurrentQueue<Exception> to pass exceptions out of threads.
- Raise events/delegates from the worker thread.
- Prefer Task, which will deliver exceptions to the await by default.
Example: collect the error in a special place
using System;
using System.Threading;
class Program
{
static Exception? threadException = null;
static void Main()
{
Thread thread = new Thread(DoWork);
thread.Start();
thread.Join();
if (threadException != null)
{
Console.WriteLine($"An error occurred in another thread: {threadException.Message}");
}
else
{
Console.WriteLine("Thread finished without errors.");
}
}
static void DoWork()
{
try
{
throw new Exception("Trouble in another thread!");
}
catch (Exception ex)
{
threadException = ex;
}
}
}
Note: this approach works for synchronous waiting (Join()). If the thread "lives on its own" or there are many errors — use ConcurrentQueue<Exception>, events or other communication mechanisms.
5. Comparison with Task: why error handling is simpler
async Task FooAsync()
{
throw new Exception("Error in the task!");
}
try
{
await FooAsync();
}
catch (Exception ex)
{
Console.WriteLine($"Caught error: {ex.Message}");
}
Here everything is transparent: the error "arrives" at the place where you await it. With a classic Thread the error stays inside the thread and isn't propagated up without special actions. This is one of the arguments for using Task and modern abstractions.
6. Practical example
In UI apps (WPF/WinForms) threads are used to avoid blocking the interface. Unhandled exceptions lead to a "grey screen" and strange hangs.
Bad (thread without error handling)
Thread thread = new Thread(() =>
{
// Think for a long time
Thread.Sleep(5000);
throw new Exception("All is lost!"); // no one will catch this
});
thread.Start();
Good (catch the error and notify the user)
Thread thread = new Thread(() =>
{
try
{
Thread.Sleep(5000);
throw new Exception("Something's wrong");
}
catch (Exception ex)
{
// You can show a MessageBox, log, or forward to the UI
Console.WriteLine($"Error in thread: {ex.Message}");
}
});
thread.Start();
7. Useful nuances
Global hook for unhandled thread exceptions
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
Console.WriteLine($"Globally caught error: {((Exception)args.ExceptionObject).Message}");
};
Thread thread = new Thread(() =>
{
throw new Exception("Exterminatus!");
});
thread.Start();
The AppDomain.CurrentDomain.UnhandledException handler fires for unhandled exceptions in threads, but it doesn't let you "resurrect" the thread or prevent process termination in .NET Framework. In .NET (Core/5+) it logs the error; the application may continue running if other threads are active.
Differences in exception handling — Thread vs Task
|
|
|
|---|---|---|
| Where to catch | Inside the thread | In the calling code (await, ContinueWith, etc.) |
| Consequences | Exception is lost/kills the thread (or whole app in .NET Framework) | Exception reaches the await point |
| Notify upwards | Only explicitly (variables, events, queues) | Via await, AggregateException when waiting synchronously |
| Logging | Must be done manually in the thread code | Usually in a try-catch around await |
| Context | Independent from the parent thread | Task uses the synchronization context of the calling code (for example, the UI context in WPF) |
8. Common mistakes when working with exceptions in Thread
Mistake #1: not catching exceptions inside the thread.
As a result you can get implicit termination of part of the app, or sometimes the whole process, often without clear diagnostics.
Mistake #2: trying to "catch" the exception from the thread in the main thread.
That doesn't work: a try-catch around thread.Join() or thread.Start() won't catch an error thrown inside the thread.
Mistake #3: losing error information.
If a thread crashed and you didn't pass the exception explicitly (variable, queue, event), you won't know the cause or details. That leads to "ghost" bugs.
Mistake #4: no logging.
Always log errors in threads, even if it seems like "nothing bad" will happen.