Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple-exception catches

Tags:

c#

exception

Is possible to catch more then one exception in the same catch block?

try
{   }
catch(XamlException s | ArgumentException a)
{   }
like image 211
gliderkite Avatar asked Dec 06 '25 19:12

gliderkite


1 Answers

Yes. If you catch a superclass, it will also catch all subclasses too:

try
{
    // Some code
}
catch(Exception e)
{
    // ...
}

If this catches more than you wanted then you can rethrow the exceptions that you didn't intend to catch by testing their type. If you do this, be careful to use the throw; syntax, and not throw e;. The latter syntax clobbers the stacktrace information.

But you can't catch two different types using the syntax you propose.

like image 194
Mark Byers Avatar answered Dec 08 '25 09:12

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!