We may need to clean up when a method is finished. Perhaps an open file needs to be closed, the buffer data should be emptied, and so on. If there is always a single exit point for each method, we can safely place our cleanup code in a location and know that it will be executed; But a method can be returned from multiple places, or our cleanup code is accidentally skipped because of an exception.
Begin
File = open ("/tmp/some_file", "W")
# ... write to the file ...
File.close End
Above, if an exception occurs when we write the file, the file remains open. Nor do we want this redundancy to occur:
Begin
File = open ("/tmp/some_file", "W")
# ... write to the file ...
File.close
Rescue
file.close
fail # raise a exception
end
This is a stupid way, when the program increases, the code will lose control, because we have to deal with every return and break.
To this end, we have added a keyword ensure to the "begin...rescue...end" system. The ensure Code field executes regardless of whether the begin block succeeds.
Begin
File = open ("/tmp/some_file", "W")
# ... write to the file ...
Rescue
# ... handle the exceptions
... Ensure
File.close # ... and this always happens.
End
You can use only ensure or only rescue, but when they are in the same begin...end field, rescue must be placed in front of the ensure.