sirdank
sirdank

Reputation: 3571

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;
}

Upvotes: 3

Views: 1032

Answers (4)

Claudio Redi
Claudio Redi

Reputation: 68400

That try/catch block make no sense. You only have to catch exceptions if you plan to do something with it but in that case nothing is done (just throwing the exception doesn't count as doing something as this is done anyway). You can safely remove it.

Upvotes: 0

Rohit Vats
Rohit Vats

Reputation: 81233

Might be case where developer doesn't want to expose actual call stack to the user because throw e resets the stack trace (so your errors would appear to originate from method where try block is applied)

However, simply throw preserve stack trace. So, this doesn't make any sense unless you have other code above throw:

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

    svnInfo = PopulateOutput(svnLog, svnUrl.ToString());
}
catch (Exception e)
{
    throw;
}

Upvotes: 2

Matt
Matt

Reputation: 6050

Yes, you should remove the try catch. You should catch the specific type of exception, also, if you try-catch, then throw, the call stack information of the original exception is lost, and the call stack information is very important for the debugging.

So, in general, don't try catch every thing.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564303

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.

Upvotes: 8

Related Questions