Catch Exception with Condition

Viewed 17673

Note: I am very happy to tell you that exception filters are now in the C# 6.0 language.

This is a thought experiment, I'm interested in your opinion: Does it make sense to you? Do you know whether something similar has already been proposed for the C# programming language? I wouldn't even know where to send such a proposal...

The idea is introducing syntax elements to catch an Exception only if it fulfills a certain condition.

One use case example is when working with COM Interop: Everything always throws a COMException. The actual distinguishing error code is contained in its message.

So what about (proposal 1):

try
{
    ...
}
catch (COMException ex where ex.Message.Contains("0x800706BA"))
{
    // RPC server unavailable
}
catch (COMException ex where ex.Message.Contains("0x80010001"))
{
    // Call rejected by callee
}

which translates to:

try
{
    ...
}
catch (COMException ex)
{
    if (ex.Message.Contains("0x800706BA"))
    {
        // RPC server unavailable
    }
    else if (ex.Message.Contains("0x80010001"))
    {
        // Call rejected by callee
    }
    else
    {
        throw;
    }
}

Similar cases are: SoapException, XmlException...


Another scenario is when exceptions are wrapped as inner exceptions within a general exception, and the catching logic should depend on the inner exception.

Say we have an API that wraps exceptions like this: catch (NumberFormatException ex) { throw new BusinessException(ex) }.

What about (proposal 2A):

try
{
    ...
}
catch (inner NumberFormatException nfex)
{
    ...
}

which translates to:

catch (Exception ex where ex.InnerException is NumberFormatException)
{
    NumberFormatException nfex = ex.InnerException;
    ...
}

or (2B):

catch (BusinessException bex inner NumberFormatException nfex)
{
    ...
}

which translates to:

catch (BusinessException bex where bex.InnerException is NumberFormatException)
{
    NumberFormatException nfex = bex.InnerException;
    ...
}

In this case (originally from Java) it could look like (2C):

catch (RemoteAccessException raex inner inner MyException mex)
{
    ...
}
7 Answers

Since c# 7.0 this kind of stuff already supported. Here is full reference. Here is code snippet.

    try
    {
        SomeOperationThatThrowsException();
    }
    catch(TheFilteredException ex ) when (ex.ErrorCode==123)
    {
        DoSomethingWhenExceptionThrown();
    }
Related