Table of contents
1.
Introduction
1.1.
Syntax
2.
The begin-rescue
2.1.
Need of begin-rescue block
2.2.
begin-rescue block
2.3.
Getting the Error
3.
Rescuing Specific Exceptions
3.1.
Standard Error
3.2.
Argument Error
3.3.
More Than One Type of Error
3.4.
Rescuing All Exceptions
4.
Frequently Asked Questions
4.1.
What is the rescue keyword in Ruby?
4.2.
What is begin rescue in Ruby?
4.3.
How do you catch errors in Ruby?
4.4.
What is a runtime error in ruby?
4.5.
What is an argument error?
5.
Conclusion
Last Updated: Mar 27, 2024

Handling exceptions with "rescue" in ruby

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

Introduction

Exception handling is a technique in Ruby that defines how to handle an error raised in a programme. An unwelcome or unexpected occurrence that occurs during the execution of a programme, i.e., at run time and disturbs the usual flow of the program's instructions, is referred to as an error. As a result, the rescue block will handle these types of problems. An Exception class, which contains several types of methods, is also provided by Ruby as a separate class for an exception.

Syntax

begin
    raise
      # block that raise’s exception

    rescue
      # block that rescue’s exception
end
You can also try this code with Online Ruby Compiler
Run Code

The begin-rescue

Ruby's exception handling starts with the begin-rescue block, similar to PHP's try-catch. In short, the begin-rescue code block can be used to handle raised exceptions without disrupting the program's execution. To put it another way, you can start executing a block of code and catch any exceptions that occur.

Let us see a simple program that will help you to understand the exception handling using the begin-rescue keyword.

Need of begin-rescue block

Code

puts 1/0
puts 4/2
You can also try this code with Online Ruby Compiler
Run Code

Output

main.rb:1:in `/': divided by 0 (ZeroDivisionError)
from main.rb:1:in `<main>'
You can also try this code with Online Ruby Compiler
Run Code

Explanation

In the above code, we get an error it says that in the first line, we are dividing the number by zero. Due to that one specific line, we are unable to run the second line too. This problem can be solved using a begin-rescue code block in the following way. (Use the begin-rescue code block whenever you are suspicious about the particular line.)

begin-rescue block

Code

begin
    puts 1/0
rescue
    puts "Hey first line has some error !!"
end
puts 4/2
You can also try this code with Online Ruby Compiler
Run Code

Output

Hey first line has some error !!
2
You can also try this code with Online Ruby Compiler
Run Code

Explanation

As we know that the first line has some errors, so we are adding that particular line to the begin-rescue block. The begin-rescue block tries to execute the particular line, and if any error occurs in the particular line, it simply skips the specific line and executes the rescue block.

As "1/0" is not a valid operation, so it executes the rescue block. Also, we can see that "puts 4/2" gets executed without any disturbance of the error that occurred due to the "1/0" operation.

Getting the Error

In the above example, the error that occurred was easy to detect manually, but in some cases, the errors are very hard to detect manually. So there is an easy way to print an incurred error.

Code

begin
    puts 1/0
rescue => e
    puts e
end
puts 4/2
You can also try this code with Online Ruby Compiler
Run Code

Output

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

Explanation

As we can see the output of the programme. We are getting the display of the error that we incurred while executing the programme.

Rescuing Specific Exceptions

While rescuing every exception reported is OK for simple implementations like generalizing API error messages, the recommended practice is to rescue just for particular exceptions. 

Standard Error

Let's update the generic begin-rescue block above to explicitly rescue StandardError errors to do this:

Syntax

begin
  # some process that has standard errors
rescue StandardError => e
  puts e
end
You can also try this code with Online Ruby Compiler
Run Code

Although the difference may be minor, if you use a class name after the rescue command, only exceptions of that type will be rescued.

Argument Error

If we wanted to rescue all argument mistakes, for example, we could build our begin-rescue block as follows:

Syntax

begin
  # some process that has argument errors
rescue ArgumentError => e
  puts e
end
You can also try this code with Online Ruby Compiler
Run Code

More Than One Type of Error

What if we need to rescue multiple exception types? A begin-rescue block can have many rescues, similar to an if-elsif-else chain, which, when combined with a check for the StandardError class, allows you to logically adjust to any and all issues that may arise:

begin
  # process with some errors
rescue ArgumentError => e
  # argument error will be displayed
rescue TypeError => e
  # type error will be displayed
rescue => e
  # rest all the errors
end
You can also try this code with Online Ruby Compiler
Run Code

Rescuing All Exceptions

The Interrupt exception would not work as expected if you rescued every child of the Exception class. However, you can use the same begin-rescue block to specify rescue all Exception exceptions if you wish to recover every exception raised in Ruby.

Syntax

begin
  # ...
rescue Exception => e
  # ...
end
You can also try this code with Online Ruby Compiler
Run Code

Frequently Asked Questions

What is the rescue keyword in Ruby?

A raised exception can be rescued to prevent it from crashing your application once it reaches the top of the call stack. In Ruby, we use the rescue keyword for that.

What is begin rescue in Ruby?

A possible exception could arise between "begin" and "rescue" in the code. The rescue block will be executed if an exception occurs.

How do you catch errors in Ruby?

You can use the rescue block to catch an exception and then use the retry statement to restart the begin block.

What is a runtime error in ruby?

When an invalid operation is attempted, the RuntimeError class is raised.

What is an argument error?

ArgumentError is a descendant of the StandardError superclass that is triggered when parameters supplied to a method are erroneous, unexpected, or invalid in some way.

Conclusion

In this article, we have discussed the exception handling in ruby using the begin-rescue block.

After reading about the exception handling in ruby using rescue keyword, 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