Little semantic pitfall of try..finally

This time I would like to point out the behaviour, that should be absolutely clear to any C# developer. When an exception is thrown inside try..finally block (without catch), and consequently in the scope of a using statement, it is bubbled up to the containing scope, rather than handled in any way. It implies that try..finally without catch has in fact nothing to do with exception handling.

I have already come across learning materials that suggest the otherwise. Let’s have a look at [1] (my own translation from Polish):

With a using clause we end up having code which is proof against exceptions

and [2]:

A finally block can be used to handle any exception

In my opinion the fact, that in the very case of try..finally apart from catch an exception is simply thrown out of the scope, is not stressed enough in the literature and claims like these above can be misleading.

Going a little bit further, I consider this as a little semantic pitfall in the language. When we think of a try statement, we immediately recall exception handling mechanism. However this time this is not the case. Maybe other languages have better (i.e. more meaningful) way of expressing the intent of a code being executed at the end of a scope. Have a look at scope(exit) and scope(failure) instructions in D language in [3].

[1]. Polish magazine “Programista”, issue 6/2013 (13) p. 26

[2]. “Programming in C#, A primer, second edition”, chapter 18.8

[3]. Three Unlikely Successful Features of D

One comment

  1. Little semantic pitfall of try..finally

    Dziękujemy za dodanie artykułu – Trackback z dotnetomaniak.pl

Leave a Reply

Your email address will not be published. Required fields are marked *

Protection against spam * Time limit is exhausted. Please reload CAPTCHA.