From c945d115a55710089ac23027c74ed32a40cd9e50 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Fri, 19 Jul 2019 11:36:12 -0700 Subject: [PATCH] Document use of ensure and else at method level [ci skip] --- doc/syntax/methods.rdoc | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/doc/syntax/methods.rdoc b/doc/syntax/methods.rdoc index 94fed45e9a..6424c9d9ec 100644 --- a/doc/syntax/methods.rdoc +++ b/doc/syntax/methods.rdoc @@ -475,6 +475,28 @@ May be written as: # handle exception end +Similarly, if you wish to always run code even if an exception is raised, +you can use +ensure+ without +begin+ and +end+: + + def my_method + # code that may raise an exception + ensure + # code that runs even if previous code raised an exception + end + +You can also combine +rescue+ with +ensure+ and/or +else+, without ++begin+ and +end+: + + def my_method + # code that may raise an exception + rescue + # handle exception + else + # only run if no exception raised above + ensure + # code that runs even if previous code raised an exception + end + If you wish to rescue an exception for only part of your method, use +begin+ and +end+. For more details see the page on {exception handling}[rdoc-ref:syntax/exceptions.rdoc].