2

I'm trying to catch some specific exception. The problem is that my program is complex and can hide this exception as a 'primary' exception or as an inner exception inside an aggregated exception. (it could also be an inner of an inner exception and so on) How do I catch this in an elegant way? What I've done so far

            catch (Exception e) when (e.InnerException is MyOwnSpecialErrorException)
            {
                var e1 = e.InnerException as MyOwnSpecialErrorException;
                success = false;
                exception = e1;
            }

and also:

        catch (MyOwnSpecialErrorException e) 
        {
            success = false;
            exception = e;
        }

Of course here I only take care in the case of one nested inner exception, and also this assumes that it is the first inner exception. Can someone think of some way?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Nika
  • 57
  • 7
  • What if the `AggregateException` contains a `MyOwnSpecialErrorException` along with other exceptions? Do you want to ignore the other exceptions in this case? – Theodor Zoulias May 22 '22 at 07:59
  • @TheodorZoulias yes, I would want to ignore them. One MyOwnSpecialErrorException is enough no matter what other exceptions occurred – Nika May 22 '22 at 08:04

1 Answers1

2

That's the more concise syntax I can think of, featuring the is operator:

bool success;
MyOwnSpecialErrorException exception;
try
{
    //...
}
catch (AggregateException aex)
    when (aex.Flatten().InnerExceptions.OfType<MyOwnSpecialErrorException>()
        .FirstOrDefault() is MyOwnSpecialErrorException myEx)
{
    success = false; exception = myEx;
}
catch (MyOwnSpecialErrorException ex)
{
    success = false; exception = ex;
}
catch
{
    success = true; // Ignore all other exceptions
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • why do we need the .Flatten() part instead of access .InnerExceptions? – Nika May 22 '22 at 09:40
  • @Nika if you know for sure that the `AggregateException` can be at most one level deep, you can get away without the [`Flatten`](https://learn.microsoft.com/en-us/dotnet/api/system.aggregateexception.flatten). – Theodor Zoulias May 22 '22 at 09:46