Skip to main content
Noble Desktop Publishing Team/4 min read

Error Handling & Exceptions

Ruby Error Handling with begin/rescue

1

Identify the Error Type

Trying to use undefined 'doggerel' raises NameError. Different problems raise different exception classes.

2

Wrap in begin / rescue / end

begin; puts doggerel; rescue; puts "No doggerel today!"; end

3

Catch Specific Exceptions

rescue NameError => e — rescue only the type you expect; let unexpected errors bubble up.

4

Raise Your Own Errors

raise StandardError, "Custom message" — surface specific failures with descriptive messages.

Build Web Development Skills at Noble Desktop

Noble Desktop's Full-Stack Web Development Certificate teaches modern web development concepts that transfer across Ruby, Python, and JavaScript stacks.

Learn the ins and outs of error handling with Ruby on Rails in our comprehensive tutorial, covering a range of topics such as handling errors, raising errors, and dealing with different types of errors.

Topics Covered in This Ruby on Rails Tutorial:

Handling Errors, Different Types of Errors, the Raise Method

Exercise Overview

In this exercise, we’ll be looking at error handling and exceptions in Ruby. Unfortunately, sometimes things go awry in our code and it’s best to be prepared. Let’s take a brief tour of Ruby’s robust error handling system.

Handling Errors

First and foremost, we should learn how to make sure our application doesn’t come crashing down just because some trifling error occurs.

  1. If Interactive Ruby isn’t running, go to/open Terminal and type the irb command.

  2. In Terminal, type:

    puts doggerel

    Terminal will return an error: NameError (undefined local variable or method 'doggerel' for main:Object) because this variable doesn’t exist. If this happened on our site while a user was browsing a page, they may see an error message rather than the page. This error would not be that important to the operation of our site, so we could just print nothing and move on, rather than show the error.

  3. As it happens, Ruby provides us with controls for this. Add the following begin…end loop:

    begin
          puts doggerel
       rescue
       puts "No doggerel today!"
       end

    rescue specifies what happens if an error occurs. Now our users won’t see an error, just the message we specified. In a real-world situation, we might use this structure to print a user-friendly error message on the screen, or, in the case of a more minor problem, we might not show the user anything, but instead quietly log it in the back-end for later review.

    If you know the type of error you want to anticipate, you can use rescue to reference that error explicitly. Notice that when we first typed puts doggerel, we got a NameError.

  4. Let’s see another type of error in Ruby. Type the following:

    2 + '2'

    Terminal will return a TypeError. You may remember this from Rails Level 1 where we also tried to add a string to an integer and Ruby got confused.

  5. Let’s try putting both types of errors together to see how we can use rescue to handle different errors in different ways. Create a new method:

    def should_break
       begin
          yield

    We’re going to pass a block (a bit of executable code) that has errors in it. yield executes the code.

  6. Next specify what will happen in the case of a NameError:

    rescue NameError
    puts "No such variable exists."
  7. Then specify what will happen in the case of a TypeError:

    rescue TypeError
       puts "Mismatch of variable types."
       end
  8. Call the method and pass it a block:

    should_break { puts doggerel }

    The NameError should appear: No such variable exists.

  9. Type the following:

    should_break { 2 + '2' }

    The TypeError should appear: Mismatch of variable types.

Raising Errors

Sometimes we need to raise our own errors when something doesn’t work in the code. As an example, let’s steer clear of copyright issues when naming our users.

  1. To initialize the user with a name, type:

    class User
       attr_accessor :name
       def initialize(name)
  2. Now we’ll raise another exception (error) that comes with Ruby. Type the following ArgumentError as shown below:

    raise ArgumentError, "Name is copyrighted" if name == 'Mickey Mouse'
       @name = name
       end

    The raise method’s syntax is very simple. It tells Ruby to throw an error and stop executing the program unless there’s some rescue code that handles the error appropriately.

  3. Create a new student:

    u = User.new("Jamie")
  4. Check if the new student’s name has been assigned:

    u.name

    Terminal should return: "Jamie"

  5. Try to create a new student called Mickey Mouse:

    u = User.new("Mickey Mouse")

    Terminal should return: ArgumentError: Name is copyrighted (If you are wondering why we picked that type of exception, it’s because the name is an argument. When we sent the name Mickey Mouse, it was an invalid argument.)

  6. Check the new student’s name again:

    u.name

    Terminal should still return "Jamie" because execution was stopped and the name Mickey Mouse was not assigned.

  7. If you need to create a new exception type, you can do so by subclassing RuntimeError (RuntimeError is the default for raise). Type the following:

    class CopyrightError < RuntimeError
       end

    You don’t actually have to put anything in the class—simply creating it is good enough.

  8. Now raise CopyrightError:

    raise CopyrightError, "Name is copyrighted"

    Congratulations, you’ve got a CopyrightError!

  9. Close the Terminal window, and if prompted click Terminate.