Here are two previous questions regarding this topic:
I was working today and thought this might be an appropriate syntax should this feature ever be added to the C# language. Anyone have any opinions about it?
The type of e
must be a base type or interface of every exception type listed.
Edit: In this example, the catch block handles either ArgumentNullException
or ArgumentOutOfRangeException
and places the exception instance in a variable of type ArgumentException
called e
. It doesn't handle any other type of ArgumentException
other than the two listed. I think there was some confusion about the associativity of the ,
and the as
.
Edit 2: If the listed exceptions all upcast to a variable of the type of e
, then the code compiles cleanly to MSIL without any casts or explicit type checks, making it faster (potentially significantly) than the current syntax of catching ArgumentException
followed by a throw;
if it's not one of the two you intended. The problem is even more obvious if you're catching Exception
and checking for two possible types to handle and rethrowing if it's something else.
try
{
}
catch (ArgumentNullException, ArgumentOutOfRangeException as ArgumentException e)
{
}