Evgenii Legotckoi
Aug. 26, 2016, 1:18 p.m.

User Guide #25 - Ruby - Exception processing: ensure

There may be cleanup work that is necessary when a method finishes its work. Perhaps an open file should be closed, buffered data should be flushed, etc. If there were always only one exit point for each method, we could confidently put our cleanup code in one place and know that it would be executed; however, a method might return from several places, or our intended cleanup code might be unexpectedly skipped because of an exception.

  1. begin
  2.   file = open("/tmp/some_file", "w")
  3.   # ... write to the file ...
  4.   file.close
  5. end

In the above, if an exception occurred during the section of code where we were writing to the file, the file would be left open. And we don't want to resort to this kind of redundancy:

  1. begin
  2.   file = open("/tmp/some_file", "w")
  3.   # ... write to the file ...
  4.   file.close
  5. rescue
  6.   file.close
  7.   fail # raise an exception
  8. end

It's clumsy, and gets out of hand when the code gets more complicated because we have to deal with every

  1. return
and
  1. break
.

For this reason we add another keyword to the "

  1. begin...rescue...end
" scheme, which is
  1. ensure
. The
  1. ensure
code block executes regardless of the success or failure of the
  1. begin
block.

  1. begin
  2.   file = open("/tmp/some_file", "w")
  3.   # ... write to the file ...
  4. rescue
  5.   # ... handle the exceptions ...
  6. ensure
  7.   file.close   # ... and this always happens.
  8. end

It is possible to use

  1. ensure
without
  1. rescue
, or vice versa, but if they are used together in the same
  1. begin...end
block, the
  1. rescue
must precede the
  1. ensure
.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    April 16, 2025, 5:08 p.m.
    Благодарю за отзыв. И вам желаю всяческих успехов!
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…