Reputation: 11626
There has already been a question posted here which is very similar. Mine is extending that question a bit more. Say you want to catch multiple types of exception but want to handle it the same way, is there a way to do something like switch case ?
switch (case)
{
case 1:
case 2:
DoSomething();
break;
case 3:
DoSomethingElse()
break;
}
Is it possible to handle few exceptions the same way . Something like
try
{
}
catch (CustomException ce)
catch (AnotherCustomException ce)
{
//basically do the same thing for these 2 kinds of exception
LogException();
}
catch (SomeOtherException ex)
{
//Do Something else
}
Upvotes: 28
Views: 32519
Reputation: 2634
This is copied from another posting, but I am pulling the code to this thread:
Catch System.Exception
and switch on the types
catch (Exception ex)
{
if (ex is FormatException || ex is OverflowException)
{
WebId = Guid.Empty;
return;
}
throw;
}
I prefer this to repeating a method call in several catch blocks.
Upvotes: 6
Reputation: 81105
In vb.net, one can use exception filters to say, e.g.
Catch Ex As Exception When TypeOf Ex is ThisException Or TypeOf Ex is ThatException
Unfortunately, for whatever reasons, the implementors of C# have as yet refused to allow exception filtering code to be written within C#.
Upvotes: 2
Reputation: 5802
I've never actually done this or anything like it, and I don't have access to a compiler for testing purposes but surely something like this would work. Not sure how to actually do the type comparison or if C# would let you replace the if statements with a case statement.
try
{
}
catch (System.Object obj)
{
Type type;
type = obj.GetType() ;
if (type == CustomException || type == AnotherCustomException)
{
//basically do the same thing for these 2 kinds of exception
LogException();
}
else if (type == SomeOtherException ex)
{
//Do Something else
}
else
{
// Wasn't an exception to handle here
throw obj;
}
}
Upvotes: -5
Reputation: 57658
Currently there is no language construct to accomplish what you want. Unless the exception all derive from a base exception you need to consider refactoring the common logic to a method and call it from the different exception handlers.
Alternatively you could do as explained in this question:
Catch multiple Exceptions at once?
Personally I tend to prefer the method-based approach.
Upvotes: 19
Reputation: 16065
You shouldn't be catching this many custom exceptions,however if you want you can create a common BaseException
and catch that.
Upvotes: 1