Table of contents
1.
Introduction
1.1.
Syntax
2.
Working of the ensure clause
3.
Feature of Ensure Clause
4.
Example
5.
Frequently Asked Questions
5.1.
What is ensure in ruby?
5.2.
What is an exception in ruby?
5.3.
What is a runtime error in Ruby?
5.4.
Does Ruby have try-catch?
5.5.
What is raise in exception?
6.
Conclusion
Last Updated: Mar 27, 2024

The "ensure" clause helpful in exception handling in ruby

Author soham Medewar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

One final clause may be included in the begin statement. The ensure clause is an optional clause. It appears after all the rescue and else clauses. It can also be used without the need for any rescue or else clauses.

The ensure clause contains code that is always executed, regardless of what happens in the code after the begin clause.

The ensure clause's purpose is to make sure that housekeeping tasks like closing files, committing or aborting transactions, and disconnecting database connections are completed. It's a powerful control structure that should be used whenever you allocate a resource (like a file handle or a database connection) to ensure proper deallocation and cleanup.

Syntax

begin
# process having some errors
rescue => e
# rescuing the process
ensure
# executing this process at any cost
end
You can also try this code with Online Ruby Compiler
Run Code

Working of the ensure clause

A point to note is that ensure clauses make exception propagation more difficult. We skipped over any mention of the ensure clauses in our previous explanation. An exception does not magically jump from the point where it is raised to the point where it is handled when it propagates. There is a propagation process in place. The Ruby interpreter looks for containing blocks and works its way up the call stack. It looks for a rescue clause in each begin statement that can handle the exception. It also looks for any ensure clauses that are associated with it and execute them all.

Feature of Ensure Clause

By initiating some other transfer of control, an ensure clause can cancel the progression of an exception. If an ensure clause throws a new exception, the new exception takes the place of the old one. Exception propagation stops, and the containing method returns if an ensure clause includes a return statement. Break and next are control statements that have the same effect: exception propagation is stopped, and the specified control transfer occurs.

The concept of a method return value is also complicated by an ensure clause. Although ensure clauses are typically used to ensure that code runs even if an exception occurs, they can also be used to guarantee that code runs before a method returns. If a begin statement's body contains a return statement, the code in the ensure clause will be executed before the method can return to its caller. Furthermore, if an ensure clause has its own return statement, it will change the method's return value.

The following example returns the value 2:

begin
 return 1 # Skip to the ensure clause before returning to caller
ensure
 return 2 # Replace the return value with this new value
end
You can also try this code with Online Ruby Compiler
Run Code

It is important to note that unless a return statement is explicitly used, an ensure clause has no effect on a method's return value. In the following example, the method returns 1, not 2:

def test
 begin return 1 ensure 2 end
end
You can also try this code with Online Ruby Compiler
Run Code

If it does not propagate an exception, the value of a begin statement is the value of the last expression evaluated in the begin, rescue, or else clauses. The ensure clause guarantees that the code will run, but it has no effect on the value of the begin statement.

Example

Code

def someMethod
    begin
      puts 15/0
    rescue Exception => e
      puts e
    ensure
      puts "Ensuring execution"
    end
end
someMethod
You can also try this code with Online Ruby Compiler
Run Code

Output

divided by 0
Ensuring execution
You can also try this code with Online Ruby Compiler
Run Code

Explanation

In the above example, we are declaring begin, rescue, and ensure clause in the someMethod function. We can see that “15/0” throws an error. But the ensure method after the rescue clause executes the process defined under it.

Frequently Asked Questions

What is ensure in ruby?

After the last rescue clause, ensure contains a block of code that is always executed when the block ends. The ensure block will be executed regardless of whether the block exits normally, raises and rescues an exception, or is terminated by an uncaught exception.

What is an exception in ruby?

An exception is an unwanted or unexpected event that occurs during the execution of a programme, i.e., at runtime, and disrupts the program's normal flow of instructions. In Ruby, descendants of the Exception class are used to connect raise methods with rescue statements in the begin and end blocks.

What is a runtime error in Ruby?

RuntimeError is a generic error class raised when an invalid operation is attempted.

Does Ruby have try-catch?

We have begin, end(default try-catch), and try-catch in Ruby to cope with these instances. Both try-catch and raise rescue to serve the same purpose.

What is raise in exception?

Raising an exception is a way of interrupting a program's usual flow of execution, signaling that an extraordinary event has occurred, and then returning to an enclosed section of the programme that was designed to respond to that scenario.

Conclusion

In this article, we have discussed the ensure clause and how it is useful in exception handling in ruby.

After reading about the use of the ensure clause in exception handling, are you not feeling excited to read/explore more articles on the topic of Ruby? Don't worry; Coding Ninjas has you covered. To learn, see History of RubyRuby is an object-oriented language, and Ruby on rails.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! 

Happy Coding!

Live masterclass