6

I have a small section of code invoking a webservice client method.

The method returns an array of messages as an out parameter. Often these messages contain details of any errors that have occured. When an error does occur an exception is also thrown.

I want to log the messages regardless of whether an exception is thrown or the type of the exception. Is logging in the finally block acceptable practice?

WebServiceClient client = GetWebServiceClient();
Console.WriteLine("Calling getUpdates...");
ItemStatus[] itemStatuses;
Message[] messages = null;
string outToken;
try
{
     outToken = client.getUpdates(inToken, out itemStatuses, out messages);
}
finally
{
     LogMessages(messages);
}
Darren
  • 68,902
  • 24
  • 138
  • 144
TonE
  • 2,975
  • 5
  • 30
  • 50
  • 1
    The arrangement is somewhat unusual, but given that it's not up for discussion what argument could there be against logging like this? It's natural and good. – Jon Jul 02 '13 at 08:52
  • 1
    What if `getUpdates` throws an exception (webservice call timed out, ...), before `messages` is assigned a useful value? – Hans Kesting Jul 02 '13 at 08:55
  • Yes, there are some circumstances where messages will be null or empty and these are checked for. I just want to be sure if messages contains anything useful it gets logged. – TonE Jul 02 '13 at 10:07

2 Answers2

6

Yes, a finally block will always be executed (Even if an exception is not thrown). So it kinda makes sense to put the Logging there in this context.

Darren
  • 68,902
  • 24
  • 138
  • 144
2

I finally block will always be executed, regardless of any exception that is thrown or not.

If this is your complete code, then it's fine. If not, I recommend some null checking before logging messages variable, since it may not be initialized when exception is thrown.

I think logging like this is perfectly fair.

EDIT:

I forgot to mention that there are some corner cases that will prevent finally from executing - which I don't believe that is your case, but it is worth mentioning (thanks Simon for pointing it out!).

Also, I like the finally approach if you want your method to log even if your method returns.

Community
  • 1
  • 1
Joel
  • 7,401
  • 4
  • 52
  • 58