Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would anyone do Catch (Exception e) { throw e; }?

Why would anyone do this? I do not understand. Can I delete this try-catch block without affecting the code?

try
{
    Collection<SvnLogEventArgs> svnLog = GetSVNRevisionsLog(lastRevision, currentRevision, svnUrl);

    svnInfo = PopulateOutput(svnLog, svnUrl.ToString());
}
catch (Exception e)
{
    throw e;
}
like image 441
sirdank Avatar asked Jan 18 '26 23:01

sirdank


1 Answers

Why would anyone do this?

You shouldn't do this. The closest you should come would be if you wanted to add some logging, in which case you should write:

try
{
  /// Do something
}
catch (Exception e)
{
   LogException(e); // Do some logging
   throw; // Don't use throw e
}

The throw statement, when used alone, preserves the exception call stack information.

That being said, if you don't have other logic (such as logging), there is absolutely no reason to catch the exception. Exceptions should only be caught if you need to either log/process them, or if you can reasonably handle the error and recover properly.

like image 106
Reed Copsey Avatar answered Jan 20 '26 14:01

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!