I want to know if I can safely write catch() only to catch all System.Exception types. Or do I\'ve to stick to catch(Exception) to accomplish this. I know for other exceptio
In a perfect world, you shouldn't use catch(Exception)
nor catch
(alone) at all, because you should never catch the generic Exception
exception. You always should catch more specific exceptions (for instance InvalidOperationException
...etc.).
In a real world, both catch(Exception)
and catch
(alone) are equivalent. I recommend using catch(Exception ex)
when you plan to reuse the exception variable only, and catch
(alone) in other cases. Just a matter of style for the second use case, but if personally find it more simple.
What's really important (even if it's out of the scope of your question) is that you never write the following piece of code:
try
{
}
catch (SpecificException ex)
{
throw ex;
}
This would reset the stack trace to the point of the throw. In the other hand:
try
{
}
catch (SpecificException)
{
throw;
}
maintain the original stack trace.