I'm trying to catch a custom exception thrown inside an async method but for some reason it always ends up being caught by the generic exception catch block. See sample code below
class Program
{
static void Main(string[] args)
{
try
{
var t = Task.Run(TestAsync);
t.Wait();
}
catch(CustomException)
{
throw;
}
catch (Exception)
{
//handle exception here
}
}
static async Task TestAsync()
{
throw new CustomException("custom error message");
}
}
class CustomException : Exception
{
public CustomException()
{
}
public CustomException(string message) : base(message)
{
}
public CustomException(string message, Exception innerException) : base(message, innerException)
{
}
protected CustomException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
To catch an exception that an async task throws, place the await expression in a try block, and catch the exception in a catch block. Uncomment the throw new Exception line in the example to demonstrate exception handling. The task's IsFaulted property is set to True , the task's Exception.
As we know, in asynchronous programming, control does not wait for the function's result and it executes the next line. So when the function throws an exception, at that moment the program control is out of the try-catch block.
You can't have async methods with ref or out parameters.
The await keyword before a promise makes JavaScript wait until that promise settles, and then: If it's an error, an exception is generated — same as if throw error were called at that very place. Otherwise, it returns the result.
The problem is that Wait
throws an AggregateException
, not the exception you are trying to catch.
You can use this:
try
{
var t = Task.Run(TestAsync);
t.Wait();
}
catch (AggregateException ex) when (ex.InnerException is CustomException)
{
throw;
}
catch (Exception)
{
//handle exception here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With