When a method ends, we may need to clean it up. maybe an open file needs to be closed, and the data in the buffer zone should be cleared. if there is always only one exit point for each method, we can safely clean up our CodePut it in one place and know that it will be executed; but a method may return from multiple places, or our cleanup code is accidentally skipped due to exceptions.
Begin
File = open ("/tmp/some_file", "W ")
#... Write to the file...
File. Close
End
If an exception occurs during file writing, the file will be retained and opened. We do not want such redundancy to occur:
Begin
File = open ("/tmp/some_file", "W ")
#... Write to the file...
File. Close
Rescue
File. Close
Fail # raise an exception
End
This is a stupid way, whenProgramWhen increasing, the code will be out of control, because we have to process every return and break ,.
To this end, we add a keyword ensure to the "begin... rescue... end" system. Whether the begin block is successful or not, the ensure code domain will be executed.
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 only use ensure or rescue, but when they are in the same begin... end field, rescue must be placed before ensure.