Attachment in creation features with exceptions

by Colin LeMahieu (modified: 2009 Jul 14)

This is a short template of what one can do when dealing with the perfect storm of complication using attached variables. This issue can arise when you need to attempt to release a resource, e.g. closing a file, that was created during a creation procedure, and you want the file to be attached in the enclosing class.

Say, for instance, in the below example we didn't use the_file' and just used an attached file'. The rescue clause would not compile because it's not assured that the creation procedure for the file completed. We need an intermediary reference that is detached, to use in the rescue clause. make_from_file (file_name: STRING) local the_file: detachable RAW_FILE -- This is the object we'll use to close the file in case of exception. do create file.make_open_read (file_name) the_file := file parse_file -- Operate on attached member variable file `file' file.close rescue if attached {RAW_FILE} the_file as x then -- If file was never created, we won't attempt to close x.close -- If there was an error while parsing, attempt to close end end file: RAW_FILE

With this creation procedure you can be sure your file will always be closed and file is an attached member of the class.

  • Manu (14 years ago 15/7/2009)

    I think you should write your creation code as:

    create file.make_open_read (file_name) the_file := file ....

    • Colin LeMahieu (14 years ago 15/7/2009)

      What's the advantage that way?

      • Colin LeMahieu (14 years ago 15/7/2009)

        I suppose in general it's better to assign to a detachable type from an attached type. In this case there isn't an issue because it's a local. I'll switch it around.