Home >Backend Development >C++ >How to Catch Exceptions Thrown in Different Threads in C#?

How to Catch Exceptions Thrown in Different Threads in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-05 14:54:46239browse

How to Catch Exceptions Thrown in Different Threads in C#?

Catching Exceptions Thrown in Different Threads

In multi-threaded programming, it can be challenging to handle exceptions that occur in threads other than the main thread. This issue arises when one method (Method1) spawns a new thread, and that thread executes another method (Method2) that throws an exception. The question is how to capture this exception within Method1.

Solution for .NET 4 and Above

For .NET 4 and later versions, Task class offers a convenient solution. It allows you to get exceptions using the .Exceptions property on the task object. Here are two approaches:

  • Handling Exceptions in Task Thread:

    class Program
    {
        static void Main(string[] args)
        {
            Task<int> task = new Task<int>(Test);
            task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);
            task.Start();
            Console.ReadLine();
        }
    
        static int Test()
        {
            throw new Exception();
        }
    
        static void ExceptionHandler(Task<int> task)
        {
            var exception = task.Exception;
            Console.WriteLine(exception);
        }
    }
  • Handling Exceptions in Caller Thread:

    class Program
    {
        static void Main(string[] args)
        {
            Task<int> task = new Task<int>(Test);
            task.Start();
    
            try
            {
                task.Wait();
            }
            catch (AggregateException ex)
            {
                Console.WriteLine(ex);
            }
    
            Console.ReadLine();
        }
    
        static int Test()
        {
            throw new Exception();
        }
    }

In both cases, you get an AggregateException, and the actual exceptions are accessible through ex.InnerExceptions.

Solution for .NET 3.5

For .NET 3.5, you can use the following approaches:

  • Handling Exceptions in Child Thread:

    class Program
    {
        static void Main(string[] args)
        {
            Exception exception = null;
            Thread thread = new Thread(() => SafeExecute(() => Test(0, 0), Handler));
            thread.Start();
    
            Console.ReadLine();
        }
    
        private static void Handler(Exception exception)
        {
            Console.WriteLine(exception);
        }
    
        private static void SafeExecute(Action test, Action<Exception> handler)
        {
            try
            {
                test.Invoke();
            }
            catch (Exception ex)
            {
                Handler(ex);
            }
        }
    
        static void Test(int a, int b)
        {
            throw new Exception();
        }
    }
  • Handling Exceptions in Caller Thread:

    class Program
    {
        static void Main(string[] args)
        {
            Exception exception = null;
            Thread thread = new Thread(() => SafeExecute(() => Test(0, 0), out exception));
    
            thread.Start();
    
            thread.Join();
    
            Console.WriteLine(exception);
    
            Console.ReadLine();
        }
    
        private static void SafeExecute(Action test, out Exception exception)
        {
            exception = null;
    
            try
            {
                test.Invoke();
            }
            catch (Exception ex)
            {
                exception = ex;
            }
        }
    
        static void Test(int a, int b)
        {
            throw new Exception();
        }
    }

These options provide flexibility in handling exceptions in multi-threaded scenarios, ensuring robust error management in your applications.

The above is the detailed content of How to Catch Exceptions Thrown in Different Threads in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn