1

In the following example exception is not intercepted and the program keeps running as if nothing happened. Is there a global error handler that can intercept such exceptions? Here's playground link.

Config

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>

Code

using System;
using System.Threading.Tasks;

class Program
  {
    static public void Main(string[] args)
    {
      try
      {
        Program.ThrowErrorInTask();
        Task.Delay(2000).Wait();
        Console.WriteLine("Exception not caught");
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex);
      }
    }
    static public void ThrowErrorInTask()
    {
      Task.Run(() =>
      {
        throw new Exception("Something happened");
      });
    }
  }
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
manidos
  • 3,244
  • 4
  • 29
  • 65

1 Answers1

4

Since your Task.Run is not awaited that's why it is considered as a fire and forget task. The Task itself can not throw exception (it only populates its Exception property), the await or .GetAwaiter().GetResult() can throw.

The TaskScheduler exposes an event called UnobservedTaskException, which is raised whenever your Task is collected by the GC and the Task is failed. The UnobservedTaskExceptionEventArgs exposes an Exception property which contains the unobserved exception.

For more details please check this SO thread: TaskScheduler.UnobservedTaskException event handler never being triggered.

Peter Csala
  • 17,736
  • 16
  • 35
  • 75