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?

2
  • What if the AggregateException contains a MyOwnSpecialErrorException along with other exceptions? Do you want to ignore the other exceptions in this case? Commented May 22, 2022 at 7:59
  • @TheodorZoulias yes, I would want to ignore them. One MyOwnSpecialErrorException is enough no matter what other exceptions occurred Commented May 22, 2022 at 8:04

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

why do we need the .Flatten() part instead of access .InnerExceptions?
@Nika if you know for sure that the AggregateException can be at most one level deep, you can get away without the Flatten.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.