You can do:
try
{
// ...
}
catch (Exception exc)
{
if (exc is IndexOutOfRangeException ||
exc is FormatException)
{
// do something
}
else
{
throw;
}
}
or:
void MethodA()
{
try
{
// ...
}
catch (IndexOutOfRangeException)
{
MethodAExceptionHandler();
}
catch (FormatException)
{
MethodAExceptionHandler();
}
}
void MethodAExceptionHandler()
{
// do something
}
But, as Arne says, it may be better to do neither because eventually it
may make sense for the handling to depend on the type of exception.
In fact, the fact that you are trying to handle two different exceptions
in the same way strongly suggests that you are already heading down the
wrong road. If you are handling two different exceptions identically,
then at the very least it's debateable whether you really ought to be
handling each one individually, as opposed to just handling a shared base
class between the two. And it's possible it's a mistake to be handling
the exceptions at all. After all, if you can treat the two disaparate
exceptions identically, just how much real exception recovery could you be
doing at that point?
It's hard to say without knowing more about the rest of the code. But you
definitely should be proceeding carefully.
Pete
Well, what I'm doing is a file renaming scheme. I have certain
characters and strings that can be replaced in the renaming process (*
- is the whole file name, | - represents an ascending number, etc.).
The problem comes when I get to the char sequence I decided on for
representing various chars in the old file name. I've decided to
implement <#>, <#-#>, and <#, #> to represent the characters from the
specific positions in the old filename.
Now, In order to give the user a sense of what the new filename will
be I process the new filename after each keystroke (and mark the files
that have the same name in red). But, when I get to the char series
<#> I get errors because of two things. One, if the # is not a number
but a letter (<A>, FormatException), the other is when the user puts
in a number that is longer than the original filename (<234>,
IndexOutOfRangeException). So far I choose to handle both of these
instances the same way, by simply ignoring the string in the renaming
process. I'm not sure yet that I want to ignore EVERY exception, but
so far these two do, in fact, have the same resolution.
On the other hand I can't think of what else to do in the event of
some other exception.
Tom P.