The following code works as expected in (the code-behind of a WPF UserControl of a .NET 4.8 project).
private async Task DeleteAsync()
{
try
{
await ViewModel.DeleteAsync(GetSelectedItems());
}
catch (Exception ex)
{
var doCatch = ex is ValidationException
|| ex is ExpectedInfoException
|| ex is ExpectedDbException;
if (doCatch)
ExeptionHelper.HandleException(ex, AppConstants.ApplicationName);
else
throw;
}
}
The following analog experiment does not always Catch an exception in a .NET 6.0 project, see inline comments. My attempt of a minimal reproducible repro sample is still not complete yet, but hopefully someone already has an educated guess for the reason?
private async void DeleteListAsync()
{
var list = ViewModel.GetSelectedItems(
dataGrid.SelectedItems.OfType<ActorModel>().ToList());
try
{
await ViewModel.DeleteListAsync(list);
}
catch (Exception ex) when (
ex is ValidationException
|| ex is ExpectedInfoException
|| ex is ExpectedDbException)
{
/* this part does run as expected when() one of those three
* custom MyNamespace.Exceptions gets thrown in the previous `try` block.
* But unexpectedly *not when thrown inside the nested step-into code of
* ViewModel.DeleteListAsync() */
ApplicationHelper.HandleException(ex, Intl.LocalizedConstants.AppName);
}
catch
{
/* this part does run as expected when a `new InvalidOperationException("Test")`
* or `NotImplementedException()` gets thrown directly in the `try`block.
* Also when thrown inside the nested step-into code of
* ViewModel.DeleteListAsync() */
throw;
}
}
[Solved]: Much later, with the help of the useful comments I actually found a missing await statement in a secluded and dark corner of the nested code, just as @Charlieface said, thank you all very much!
You apparently have a missing await somewhere in your code, which is causing an exception to be wrapped in an AggregateException.
One of the things that await does, as well as setting up the state machinery, is to unwrap AggregateExceptions which hold any exceptions that were thrown during the running of the Task. Therefore, if you want to catch and handle a specific exception type, you should use await all the way down.