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 put our cleaning code 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. When the program increases, the code will be out of control, because we have to deal with 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.