๐ŸŽ“ A1Learner
๐Ÿ”

Ruby Errors

An error message is the text a program prints when it stops on a problem. Its first line names the file and the line, tells what went wrong and ends with the error class.

NameError

This program tries to print the name score. The name was never given a value, so the run stops at once.

puts score

NoMethodError

This program calls a method named lenght on a string. A string has no method with that name, so the run stops at once.

puts "hello".lenght

TypeError

This program adds the number 42 to a string. Text and a number cannot join with +, so the run stops at once.

puts "Score: " + 42

ZeroDivisionError

This program divides 10 by 0 with no rescue block. The run stops at once and prints the error.

puts 10 / 0

Example

begin
  puts 10 / 0
rescue => e
  puts e.class
end

Key points

  • The first line of an error message carries the main facts.
  • The start of the line names the file and the line number.
  • The middle of the line tells what went wrong.
  • The error class sits at the end inside round brackets.
  • A NameError means the program used a name that was never given a value.
  • A NoMethodError means a value has no method with that name.
  • A TypeError means values of the wrong type were combined.
  • A ZeroDivisionError means a number was divided by zero.

In this example, the begin block tries 10 / 0 and the division fails. The rescue line saves the error in e. The last line prints the class of that error.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Ruby Compiler

Exercise

What does the end of the first error line name?