Handling Exceptions in Ruby

People holding blocks of letter written ERROR

When I started working on my first CLI project, I encountered many errors and spent most of my time debugging, which is good because I have read somewhere that “Only half of programming is coding. The other 90% is debugging.” After digging through ruby docs, I found out about these useful keywords, begin and rescue.

Let me give you a refresher! Keywords or reserved words are used by a language for internal processes and therefore cannot be used as a variable.

For example:

#'if' and 'end' are keywords to check the condition of a given code.
#Here 'if' is checking some condition
if 2 > 1 puts "I love Ruby"end # "I love Ruby"#"if' cannot be used as a variable
#'if' has been already reserved by the ruby language
if = 2 # : syntax error, unexpected '=')

Although there are a bunch of keywords in ruby, I will be focusing on begin and rescue. They are also known as exception handlers. In ruby whenever an exception occurs, it terminates the execution of our program, this is where the exception handlers come into play. The code in your project, that may raise an error or exception can be enclosed within the begin…end block, followed by a code that is written in the rescue block to handle this error:

def some_condition
puts 3/0
end
#=> divided by 0 (ZeroDivisionError)

The above code is giving us a ZeroDivisonError. Let's handle this error together!

def some_condition
begin
puts 10/0
rescue
puts 10/2
end
end
some_condition #=> 5

As expected, this method returned 5! We know, in ruby, a number cannot be divided by zero, and so it will raise an exception. So we wrote the “problematic” code inside the begin block. The code got executed but did not break our program. Instead, it ran the code under the rescue block and returned us with a nice answer! Phew, without an error! Keep in mind that if the code inside the begin block does not raise any possible errors, the code will be executed just fine. The rescue will only be executed when there is an error!

There will be a number of scenarios, where you will also want to see the error messages even after the program is being rescued. Let’s see how it works but this time with a different exception:

def some_condition
puts "hello".even?
end
some_condition #=> in `some_condition': undefined method `even?' for "hello":String (NoMethodError)

Let’s not break the program and still print the error message:

def some_condition
begin
puts "hello".even?
rescue Exception => e #Exception object is being saved to a variable
puts "hello".length
puts e.message #prints the error message
end
end
some_condition
#=> 5
#=> undefined method `even?' for "hello":String

Nice! We have handled our error successfully! We were able to rescue our program as well as print the error message. So what exactly are we doing here? We saved the Exception class to a variable “e”, and now the error message can be printed in the rescue block. Since we already know the type of error, we can rewrite our code like this:

def some_condition
begin
puts "hello".even?
rescue NoMethodError => e
puts "hello".length
puts e.message #prints the error message
end
end
#returns the same result

Please copy-paste these codes and play around with the errors for better understanding! Happy error handling!

Coach @FlatironSchool

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store