Details about the registration exception in the try finally block

I have a small section of code that calls the webservice client method.

The method returns an array of messages as an out parameter. Often these messages contain information about any errors that occurred. If an error occurs, an exception is also thrown.

I want to log messages regardless of whether an exception or exception type is selected. Is end block registration an 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); } 
+4
source share
2 answers

Yes, the finally block will always be executed (even if no exception is thrown). Therefore, it makes sense to put a magazine in this context.

+5
source
Block

I finally will always be executed regardless of any exception thrown.

If this is your complete code, then this is normal. If not, I recommend some kind of zero checking before writing variable messages, since it cannot be initialized when an exception is thrown.

I think that registration like this is completely fair.

EDIT:

I forgot to mention that there are some corner cases that will not allow final execution - that I do not think this is your case, but worth mentioning (thanks Simon for pointing out!).

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

+2
source

Source: https://habr.com/ru/post/1489236/


All Articles