Steve said:
I have some general catch clauses in my app as follows:
try
{
}
catch(Exception ex)
{
}
try
{
}
catch(Exception ex)
{
}
try
{
}
catch(SystemException ex)
{
}
I analyzed the code with Microsoft FxCop.
The FxCop warned me that "Generic exceptions should not be caught".
Could anyone explain what is wrong with usage of general catch clauses?
FxCop is wrong. You can catch Exception, you just can't eat it. It's a
Catch and Release only item.
Generic exceptions should often be caught, but they shoud usually be
rethrown or wrapped and rethrown.
You might catch Exception in order to capture stack data (arguments) which
will dissappear when the exception propagates back up the stack.
eg:
void foo(string s)
{
try
{
..do domething
}
catch(Exception ex)
{
throw new MyAppException("foo failed with argument s=" + s,ex);
}
}
or
void foo(string s)
{
try
{
..do domething
}
catch(Exception ex)
{
Trace.WriteLine("foo failed with argument s=[" + s + "] because " +
ex.Message);
throw;
}
}
There are many situations where it is inappropriate or unnecessary to catch
Exception, but it's not a general rule. If you are running a SqlCommand,
you should catch SqlException, not Exception. And you should never catch
Exception and then try to recover. Exception includes things like
ExecutionEngineExeption, OutOfMemoryException, ThreadAbortException and
StackOverflowException. You should never try to recover from these.
David