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.
Both constructs (catch ()
being a syntax error, as sh4nx0r rightfully pointed out) behave the same in C#. The fact that both are allowed is probably something the language inherited from C++ syntax.
Others languages, including C++/CLI, can throw
objects that do not derive from System.Exception
. In these languages, catch
will handle those non-CLS exceptions, but catch (Exception)
won't.
If the fact that an exception occurs implies that you need to run a piece of code, but you wouldn't do anything with the exception except rethrow it if you caught it, the preferred approach is probably not to catch the exception but instead do something like:
bool ok=false; try { ... do stuff -- see note below about 'return' ok = true; } finally { if (!ok) { ... cleanup code here } }
The one weakness with this pattern is that one must manually add an ok = true;
before any return statement that occurs within the try
block (and ensure that there's no way an exception (other than perhaps ThreadAbortException) can occur between the ok = true;
and the return). Otherwise, if one isn't going to do anything with an exception, one shouldn't catch it.
catch(Exception ex)
can handle all exceptions which are derived from System.Exception
class, however if the exception thrown is not derived from System.Exception
then it will not be handled by catch(Exception ex)
.
Prior to .NET 3.0 exceptions thrown by unsafe code (i.e. code not targeting CLR) were handled by catch{}
. After .NET Framework 3.0 all types of exception can be handled by System.Exception
class. catch{}
is now obsolete .
Take a look at this link: http://msdn.microsoft.com/en-gb/library/0yd65esw.aspx
I think it will be ok, have or not but you can let argument in statement catch to get exactly the exception that you want and handle them rightly.