In my opinion, there is only one reason why you should not <<< โ << โ or "in", as Mason pointed out ) a try / finally .
- If the lifetime of objects is controlled by another object.
This management can take three forms:
- A reference to an object has a scope outside the local block and is freed up in another place - as a field element freed in the destructor.
- An object immediately added to the list, which is responsible for freeing the object later.
- An object with an associated lifecycle manager, for example, how to transfer ownership to a VCL control during construction.
C # 1 , when a link has a wider scope, the link should immediately be set to zero unless it is built immediately. That way, when it is checked for reference, you know that you have an accurate reading. This is most common with member objects that are created as part of a larger class and then cleared when the parent object is destroyed.
C # 2 , when an object is added to the list, you want to use the try-except block (one of several times when I use it) only if an exception occurs after the object is built and before it is added to the control list. Ideally, the first line after building adds it to the list, or the list is actually a factory class that gives you an object already added to the list.
C # 3 , when an object has another lifetime manager, you really need to make sure that managing this manager is the right thing. If you create a VCL control, you may be tempted to have your own form (or any other control), but this actually imposes additional construction and destruction overheads. If this is possible, you should explicitly release it, this is especially true if you install the control once, then you know that you release it in your form destructor or when it closes. The only time you cannot do this is to make the control more dynamic.
So, it is best to use a lot of try / finally blocks. You should only have a few try / except blocks, and most of them should catch special types of exceptions and / or raise the exception again. If you have more try / except than try / finally blocks, then you are doing it wrong .
Jim mckeeth
source share