C# 7 Pattern Matching
You cannot declare ve
variable twice in same scope. But you can rewrite exception filter so that variable for ValueException<int>
will be declared only once:
catch(Exception e)
when (((e as AggregateException)?.InnerException ?? e) is ValueException<int> ve)
{
// ...
}
It's your one-liner to catch exception if it either was thrown directly or if it is wrapped into AggregateException
.
Keep in mind that purpose of AggregateException
is consolidating multiple exceptions into one exception object. There could be several inner exceptions, and some of them can be aggregate exceptions as well. So you should flatten aggregate exception and check all of its inner exceptions.
You can put 'unwrapping' part into extension method to improve readability of your code.
Not as nice as Sergey's solution, but you can also use different names and coalesque them:
try
{
...
} catch (Exception e)
when (e is AggregateException ae && ae.InnerException is ValueException<int> ve1
|| e is ValueException<int> ve2)
{
var exept = ve1 ?? ve2;
// do something with exept
}
if you handle InnerExceptions of ValueException or general ValueException Exceptions the same.