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");
});
}
}
CodePudding user response:
Since your Task.Run
is not await
ed that's why it it considered as a fire and forget task. The Task
itself could not throw exception (it only populates its Exception
property), the await
or .GetAwaiter().GetResult()
can.
The TaskScheduler
exposes an event called UnobservedTaskException, which is raised whenever your Task is collected by the GC and it 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.