49 Days of Ruby: Day 19 - Exceptions

Ben Greenberg - Apr 15 '21 - - Dev Community

Welcome to day 19 of the 49 Days of Ruby! 🎉

Today we are going to discuss a topic that can strike fear in the hearts of developers everywhere! 😱 We are talking about exceptions. Why are they so scary?

Take a look at this:

irb(main):001:0> puts "Hi, #{name}"
Traceback (most recent call last):
        4: from /Users/bengreenberg/.asdf/installs/ruby/2.7.2/bin/irb:23:in `<main>'
        3: from /Users/bengreenberg/.asdf/installs/ruby/2.7.2/bin/irb:23:in `load'
        2: from /Users/bengreenberg/.asdf/installs/ruby/2.7.2/lib/ruby/gems/2.7.0/gems/irb-1.2.6/exe/irb:11:in `<top (required)>'
        1: from (irb):1
NameError (undefined local variable or method `name' for main:Object)
Enter fullscreen mode Exit fullscreen mode

We start seeing a lot of things that don't make a lot of sense to us. Items like Traceback (most recent call last) and NameError. It's no wonder that exceptions are intimidating.

What specifically is an exception?

An exception is a language, in this case, Ruby, telling us that something is not quite right.

Exceptions are actually trying to be helpful. Let's break down the example above to see what we mean.

Exceptions in Ruby

In the above example, I tried to output the following interpolated string: "Hi, #{name}". That looks okay, what could be wrong? What does the exception say?

NameError (undefined local variable or method `name' for main:Object)
Enter fullscreen mode Exit fullscreen mode

If we look closely we see it says that there is an undefined local variable or method called name. This is called a NameError. What do you think that means?

Perhaps you think it means Ruby is trying to tell us we don't have a variable called name? You would be right!

We can view exceptions as guides along our development journey. They can help us return back to the path when we veered off course.

There are many different sub-classes of the main Exception class. Each sub-class is communicating a different type of error. The NameClass is an example of one of those sub-classes.

The Ruby docs list all the different sub-classes, and you can even click through to read about each one!

The more you familiarize yourself with exceptions, the more helpful they will be in debugging what went wrong when things inevitably go wrong in your code.

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player