'How to catch an exception in a task?

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");
      });
    }
  }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source