Prev - DUP - Next - TOC

Don't forget to close the door (ensure)


Some processes need to be finished up. For example, we should close an opened file, flush data which is stored in the buffers, etc. If there is only one exit for each method, we may put anything to be done there, however, a method returns from various conditions and we must consider the alternative way to ensure finishing the process. Ruby also has `exception', which increases the way to return. See the following for instance:

 ruby> begin
 ruby|   file = open("/tmp/some_file", "w")
 ruby|   # something to do
 ruby|   file.close
 ruby| end

In the above, if an exception occurred while ``something to do'' the file will be left open. Though the file should be closed, we don't want the following:

 ruby> begin
 ruby|   file = open("/tmp/some_file", "w")
 ruby|   # something to do
 ruby|   file.close
 ruby| rescue
 ruby|   file.close
 ruby|   fail # raise an exception
 ruby| end

It is too complicated to write, and one must respond for each return or break.

For such situations, ruby has a syntax to describe a finishing up. If an ensure clause is put in begin, the clause is executed always.

 ruby> begin
 ruby|   file = open("/tmp/some_file", "w")
 ruby|   # something to do
 ruby| ensure
 ruby|   file.close
 ruby| end

The section specified by ensure is sure to be executed, so the programmer doesn't need to worry to close the file.

By the way, if one specifies both rescue and ensure in a begin, the rescue must go ahead of the ensure.


Prev - DUP - Next - TOC