Ruby Exception Handling: Ensure_ruby topics

Source: Internet
Author: User
Tags exception handling
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 an 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.
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.