> My objective is to make sure that the utility method is fail-safe. In other
Yes, but don't take "fail-safe" to extremes. If you catch an
OutOfMemoryException, is your method really being "fail-safe", or are
you just swallowing an important exception and doing nothing with it? I
would say the latter. You haven't helped your caller out any by
throwing away a system-level exception like OutOfMemoryException.
The general rule is simple: catch only exceptions with which you can
deal intelligently. There are only three situations in which I catch
1. When I want to transform the exception into a return value. For
example, in your case you want ArgumentNullException, FormatException,
and OverflowException to be transformed into a return of false,
indicating "this is not an integer." That's fair: each of those
exceptions is meaningful to you and your callers, it's just that you
want to change the way the caller receives that information: as a
return value rather than exception. OutOfMemoryException, on the other
hand, does _not_ mean "this is not an integer." It means that something
went horribly wrong deep inside the .NET Framework, so it's not
appropriate to transform it into a return value.
2. When I want to transform the exception into a different exception,
because the low-level exception isn't meaningful from the point of view
of the caller. For example, I might want to transform a
DivideByZeroException into an InvalidArgumentException, because it's
more appropriate to tell my caller that they passed an invalid
argument; my caller doesn't care that I later used that argument in a
division operation. (Yes, I know, bad programming practice: better to
check for zero up front. :-)
3. When I know that I can recover from the specific situation that a
specific exception indicates. For example, I might get an exception
attempting to parse an XML file against a schema, but my application
can recover from that situation by running the XML through a transform
to bring it up to the latest version. In this case, I catch the
exception and then take a different path through my app. This includes
the case in which my application might want to ignore a particular
exception and keep going anyway.
The bottom line in all three cases is that I catch a specific exception
when I know that I can do something meaningful with that exception.
Never catch an exception if you then don't know what to do with it.
In the case of an OutOfMemoryException, what is your method going to do
with it? Toss it away and keep going anyway? Is that a decision for
your method to make, or is that a higher-level decision for the calling
application? I would say the latter.