This is a related Q: Is use of finally clause for doing work after return bad style/dangerous?
In the referenced Q, the finally code is related to the structure used and the necessity of pre-fetching. My question is a little different, and I believe it's germane to the broader audience. My particular example is a C# winform app, but this would apply to C++ / Java finally usage as well.
I'm noticing quite a few try-catch-finally blocks where there is a lot of code unrelated to exceptions and exception handling / cleanup buried within the block. And I will admit my bias towards having very tight try-catch-finally blocks with the code closely related to the exception and handling. Here are some examples of what I'm seeing.
Try blocks will have lots of preliminary calls and variables being set leading up to the code that could throw. Logging information will get setup and run in the try block as well.
Finally blocks will have form / module / control formatting calls (despite the app being about to terminate, as expressed in the catch block), as well as creating new objects such as panels.
Roughly:
methodName( ... ) { try { // Lots of code for the method ... // code that could throw ... // Lots more code for the method and a return ... } catch( something ) { // handle exception } finally { // some cleanup due to exception, closing things // more code for the stuff that was created (ignoring that any exceptions could have thrown) ... // maybe create some more objects } }
The code works, so there is some value to it. It is not well encapsulated and the logic is a bit convoluted. I'm (painfully) familiar with the risks in shifting code around as well as refactoring, so my question boils down to wanting to know others' experience with similarly structured code.
Does the bad style justify making the changes? Has anyone been badly burned from a similar situation? Would you care to share the details of that bad experience? Leave it be because I'm over-reacting and it's not that bad of style? Gain the maintenance benefits of tidying things up?
finally
. All good uses are covered under RAII/RRID/SBRM (whichever acronym you like).finally
does in C#). What is the C++ equivalent? What I'm thinking of is code after thecatch
, and that applies the same for code after the C#finally
.Environment.FailFast()
; it may not be executed if you have an uncaught exception. And it gets even more complicated if you have an iterator block withfinally
that you iterate manually.