Yurii Hohan
Yurii Hohan

Reputation: 4171

Calling methods which might throw inside catch

Let us say we have an external server which we use (e.g.-telephony station, etc.). Also we have the next code:

try
{
   externalService.CreateCall(callParams);
}
catch (Exception ex)
{
   _log.Error("Unexpected exception when trying execute an external code.", ex);
   _callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
   throw;
}

Theoretically UpdateCallState could throw but we would hide this exception using that code and would treat only exceptions generated by CreateCall in a right way.

The question is, what is the right pattern for these situations so that we treat all the exceptions correctly?

Upvotes: 2

Views: 2925

Answers (4)

Jamiec
Jamiec

Reputation: 136124

You can always nest another try..catch inside the first catch and deal with it appropriately.

try
{
   externalService.CreateCall(callParams);
}
catch (Exception ex)
{
   _log.Error("Unexpected exception when trying execute an external code.", ex);
   try
   {
       _callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
   }
   catch(Exception updateEx)
   {
       // do something here, don't just swallow the exception
   }
   throw; // this still rethrows the original exception
}

Upvotes: 5

Sandeep
Sandeep

Reputation: 7334

It is not a good practice to throw exception in Catch block.

The try, Catch suggest that

 try
{
 //make some changes. If something goes wrong go to Catch.
}

Catch(exception)
{
 //I will clean the mess. Rollback the changes.
}

Catch the exception, only if you can handle the exception. Else bubble it up let the caller decide on what to do with the exception.

Upvotes: 0

kerzek
kerzek

Reputation: 510

You should catch the most specific exception first, followed by the most general exceptions.

try
{
   externalService.CreateCall(callParams);
}
catch (CreateCallExceptionType ccEx)
{       
   _callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
catch (Exception ex)
{       
   //do something
}

And then you could handle the UpdateCallState exception within the method.

Upvotes: -1

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Break it up. Something like

if !TryCreateExternalCall(callParams)
{
  _log.Error("Unexpected exception when trying execute an external code.", ex);
  _callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed); 
}
else
{
  throw new ExternalServiceException(???);
}

TryCreateExternalCall should of course log the exception and stacktrace, before it swallows and returns false.

Upvotes: 0

Related Questions