gliderkite
gliderkite

Reputation: 8928

Multiple-exception catches

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

try
{   }
catch(XamlException s | ArgumentException a)
{   }

Upvotes: 2

Views: 674

Answers (5)

supercat
supercat

Reputation: 81347

In vb.net, it is possible to say Catch Ex As Exception When IsMyException(Ex), where IsMyException is any desired function which examines Ex and decides whether or not to catch it. The determination of whether or not to catch Ex is made before any inner Finally blocks run. Unfortunately, the makers of C# dislike the idea of allowing custom exception filters, perhaps because it would pollute the language with platform-specific details (most platforms could not support .net-style exception filters). Consequently, the best one can hope for in C# is to do something like:

void HandleThisOrThatException(BaseTypeOfThisThatTheOtherException)
{ ... }

...
// Catch ThisException or ThatException, but not TheOtherException
  catch (ThisException ex) {HandleThisOrThatException(ex);}
  catch (ThatException ex) {HandleThisOrThatException(ex);}

Upvotes: 1

mschr
mschr

Reputation: 8641

Not being no C# guru however, this is standard in any oop language.

    try
    {
        string s = null;
        ProcessString(s);
    }
    // Most specific:
    catch (InvalidCastException e) { out_one(e); }
    catch (ArgumentNullException e) { out_two(e); }

    // Least specific - anything will get caught
    // here as all exceptions derive from this superclass
    catch (Exception e)
    {
        // performance-wise, this would be better off positioned as
        // a catch block of its own, calling a function (not forking an if)
        if((e is SystemException) { out_two(); }
        else { System..... }
    }

Upvotes: 2

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 62012

It's a bad example because any ArgumentException is also a SystemException, so catching all SystemExceptions would implicitly get the ArgumentExceptions as well.

Upvotes: 0

D Stanley
D Stanley

Reputation: 152654

Not as succinctly as you are asking. One way would be to catch all exceptions and handle those two specially:

catch(Exception e)
{   
  if((e is SystemException) || (e is ArgumentException))
     // handle, rethrow, etc.
  else
     throw;
}

Upvotes: 3

Mark Byers
Mark Byers

Reputation: 839254

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.

Upvotes: 7

Related Questions