roslyn: Catch multiple exceptions instead of when keyword

Handle multiple exceptions in C# we need to use when keyword, So In C# 7.0 can we please simplify this like below.

Expected Behavior:

try
{
}
catch(FormatException || OverflowException ex)
{
}

Actual Behavior:

catch(Exception ex) when (ex is FormatException || ex is OverflowException ex)
{
}

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 11
  • Comments: 15 (1 by maintainers)

Most upvoted comments

Why not loosen the restrictions and allow to allow single lines to fall through instead of the {} blocks? It would be a similar idea to a case statement. It has precedence in other blocks in the language, in using statements you can do something similar. For example, you could then do something like this to get the base exception using the ?? operator without having to complicate the meaning of the catch.

try 
{
// some code here...
}
catch (IOException io)
catch (Exception ex)
{
    var finalException = (io ?? ex);
}
finaly
{
// some code here...
}

Fall-through wouldn’t make sense. None of the identifiers would be definitely assigned and assigning null to them would be contrary to how C# normally behaves.

If I were to vote on a syntax/behavior now I would go for the original proposal, which is basically what Java supports:

try {
    doSomething();
}
catch (Exception1 | Exception2 exception) {
    // exception is of the common ancestor here
    exception.printStackTrace(System.err);
}

Personally I think that the whole concept should be put off until union types and/or pattern matching further progresses. Union types would make the above nicer by allowing access to common members, which couldn’t be done after the fact as it would be a breaking change due to member shadowing. Pattern matching with an OR pattern could open up the possibilities further, perhaps allowing deconstruction directly in the catch clause.