How to Handle Exceptions in Ruby

Occasionally, a method will encounter an error, at which point it will fail and tell you about it via the a mechanism called an exception. In Ruby, when exceptions are raised by a method that encounters an error, you'll have rescue your program and handle the error.

Instructions

  1. Throw an Exception

    • 1

      Write some code that will throw an exception, using the raise statement. In Ruby, the raise statement will stop execution of the method, then unwind the program.

    • 2

      Enclose the call to this method in a matching rescue statement. Otherwise, the program will end and an error message will be displayed on the terminal. The following example shows an averaging function, such as that found in grade book software.

    • 3

      Here, all the test scores are averaged. If the result is more than 100%, there's no choice but to raise an exception because someone has cheated:
      def average(num1, num2, num3)
      av = (num1 + num2 + num3) / 3.0
      if av > 100
      raise "Someone cheated, average is #{av}"
      else
      return av
      end
      end

    Handle the Exception

    • 4

      Write the rescue statement, calling the average method enclosed in a block with a rescue statement.

    • 5

      Start the block with "begin." It can have any number of "rescue" statements, and it ends with the "end" keyword. The rescue statement has a type clause as well: a type followed by => and a variable name. Excluding the type will allow the rescue statement to catch all exceptions thrown.

    • 6

      When executing the rescue statement, the value that was raised is assigned to "e." There can be multiple rescue statements with multiple types to handle different types of errors:
      begin
      average(98, 92, 130)rescue => e
      puts "I caught someone cheating!"
      puts "The error message was this: #{e}"
      end

    Write Else and Ensure Statements

    • 7

      Create an ensure statement, in addition to the rescue statement. The ensure statement always gets executed when the block is finished. Regardless of how the block exited, whether or not there was an exception raised, or even if it failed to rescue the exception itself, the ensure statement is always executed. The else statement is only executed if there were no exceptions.

    • 8

      Here you want to make sure the grade book gets closed, so you ensure close_grade book is called:
      begin
      average(98, 92, 130)rescue => e
      puts "I caught someone cheating!"
      puts "The error message was this: #{e}">ensure
      close_gradebook
      end

    • 9

      Write an else statement. If there were no exceptions, the else statement will congratulate the student for not cheating:
      else
      puts "Good job, and you didn't even cheat!"

Tips & Warnings

  • The block is a piece of code that gets executed every time the loop is run.

Related Searches:

Comments

You May Also Like

  • How to Compare Strings in Ruby

    Ruby is an extremely powerful programming/scripting language. With powerful capabilities and an efficient syntax, many things are possible with Ruby. This article...

  • Spider-Man Arcade Games

    Spider-Man Arcade Games. As one of Marvel's most popular characters, Spider-Man has appeared in numerous video games, including games originally released in...

  • How to Use Jewels to Decorate a Table

    A lot of people like to decorate their tables for holidays. That is especially true around Thanksgiving and Christmas. While some stick...

  • How to Output a File in Ruby

    Ruby has a variety of ways which make it simple to output a file, depending on what you want to do with...

  • How to Fix the Internal Clock in "Pokémon Fire Red"

    If you are using a Game Boy Advance emulator called VisualBoy Advanced to play "Pokémon Fire Red" and you get an error...

  • How to Throw Exception in Java

    Error handling provides a way for Java developers to program responses to software errors. When a user enters a wrong value or...

  • How to Program a Robot

    Robots are an amazing feat of man’s intellect. We’ve become creatures with the capabilities to make tools so advanced that they literally...

  • Java Exceptions Tutorial

    An exception occurs when an abnormal situation (such as an error or problem) occurs that a method is unable to handle. The...

  • How to Handle a Null Pointer Exception in Java

    The Java Programming Language suffers from null pointer exceptions when a piece of information it is looking for no longer exists in...

  • How to Use Love Stones

    Some people believe that every living thing and part of mother earth hold important energies. Those who are in-tune can use these...

  • How to Catch a Minun

    Pokemon is a Game Boy game where players take control of a Pokemon trainer who captures and collects pocket monsters around the...

  • How to Get Regirock on Pokemon Ruby

    Since debuting in 1995, the Pokémon game franchise has become the second most popular video game series in the world, selling more...

  • What Is a Null Pointer Exception?

    Every Java programmer eventually writes a program that produces the "NullPointerExceptions" error message. It is particularly cryptic to those who are beginning...

  • How to Find the Regis in Pokemon

    The Regis (Regirock, Regice and Registeel) are three Pokémon available in Pokémon Ruby/Sapphire. In Pokémon Diamond/Pearl, you can also get Regigigas. As...

  • Ruby Wedding Gifts for Men

    Ruby Wedding Gifts for Men. Forty years of marriage signifies a couple's remarkable commitment to their marriage. Celebrate your ruby anniversary with...

  • Hummingbird Classification

    All hummingbirds are in the kingdom Animalia, phylum Chordata, class Aves, order Apodiformes and family Trochilidae. Only genus and species vary according...

  • How to Create a Custom Exception in Java

    Exceptions are a key tool in helping Java programs cope with the unexpected. As a developer, you can use the standard exception...

Related Ads

Featured