Nika
Nika

Reputation: 57

Catch exceptions in multi threads and processes program

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?

Upvotes: 2

Views: 52

Answers (1)

Theodor Zoulias
Theodor Zoulias

Reputation: 43941

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
}

Upvotes: 2

Related Questions