Ruby Exception Handling: Ensure

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.