no9
no9

Reputation: 6544

Returning result in nested try catch block

I am implementing some performance counters and I would like to know your opinion. The question is should I declare response and return it outside try block or Is it OK to return it directly in the try block. Is there a difference and If so, what sample code is valid (if any).

With best regards, no9.

public string TestMethod(string document)
{
  try
  {
    WebService ws = new WebService();
    string response = null;
    var startTime = PerformanceCounter.GetPerformanceCounterStartTimeHandle();

    try
    {
      response = ws.InsertDocument(document);
    }
    catch (Exception ex)
    {
      PerformanceCounterHelper.Increment(PerformanceCounterEnum.NumberOfExternalWsCallsExceptionOnSec);
      throw;
    }
    finally
    {
      PerformanceCounterHelper.IncrementPerformanceCounterByElapsedTime(PerformanceCounterEnum.DurationOfExternalCallsInSec, startTime);
      PerformanceCounterHelper.Increment(PerformanceCounterEnum.NumberOfExternalCallsOnSec);
    }

    return response;
  }
  catch (Exception ex)
  {
    log.EventError(ex);
    throw new DocumentGeneralException();
  }
}

versus:

public string TestMethod(string document)
{
  try
  {
    WebService ws = new WebService();
    var startTime = PerformanceCounter.GetPerformanceCounterStartTimeHandle();

    try
    {
      return ws.InsertDocument(document);
    }
    catch (Exception ex)
    {
      PerformanceCounterHelper.Increment(PerformanceCounterEnum.NumberOfExternalWsCallsExceptionOnSec);
      throw;
    }
    finally
    {
      PerformanceCounterHelper.IncrementPerformanceCounterByElapsedTime(PerformanceCounterEnum.DurationOfExternalCallsInSec, startTime);
      PerformanceCounterHelper.Increment(PerformanceCounterEnum.NumberOfExternalCallsOnSec);
    }
  }
  catch (Exception ex)
  {
    log.EventError(ex);
    throw new DocumentGeneralException();
  }
}

Upvotes: 1

Views: 409

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063884

As long as there isn't a difference because of not exiting (i.e. it runs additional/different code), then the code is identical. Actually, at the IL level it is illegal to ret from inside a try/catch, so one of the things the compiler does is to do exactly what you have done: introduce a local, assign the local inside the try/catch, then return that value when outside the try/catch.

Basically, go with whatever is simplest and most convenient to read. In your case, I would say "the first one".

Upvotes: 1

Related Questions