Error Handling & Exceptions

Free Ruby on Rails Tutorial

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.

This exercise is excerpted from Noble Desktop’s past web development training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

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.

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.
  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
    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
    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.

Noble Desktop Publishing Team

The Noble Desktop Publishing Team includes writers, editors, instructors, and industry experts who collaborate to publish up-to-date content on today's top skills and software. From career guides to software tutorials to introductory video courses, Noble aims to produce relevant learning resources for people interested in coding, design, data, marketing, and other in-demand professions.

More articles by Noble Desktop Publishing Team

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram