Ruby Monstas


Error Messages

2 types of errors

  • Syntax errors
  • Runtime errors

Analogy: Recipe

Understanding a recipe

(Syntax)

Cooking the recipe

(Runtime)

Syntax errors

  • Occurs before actually executing the code.
  • Code doesn't adhere to the syntax rules of Ruby.
  • Syntax highlighting can help avoid these errors.
def break_words(stuff)
  words = stuff.split(' ')
  return words
ed
break_words.rb:4: syntax error, unexpected end-of-input, expecting `end'

(the end keyword is mistyped on line 4)

Syntax errors: Another Example

[1, 2, 3].each
  puts integer
end
each.rb:3: syntax error, unexpected `end', expecting end-of-input

(after .each it expects a keyword do)

Runtime errors

  • Occurs during execution of the code.
  • Includes a backtrace/stacktrace.
  • Logic, naming, unexpected input, ...
food = "Hot Dogs"
puts "I like #{fod}"
Traceback (most recent call last):
hotdog.rb:2:in `<main>': undefined local variable or method `fod' for main:Object (NameError)
Did you mean?  food
               for

Runtime stacktraces

They tell us exactly where Ruby has been before something went wrong.

Like Hansel and Gretel's breadcrumbs to find their way out of the forest.

Image: https://upload.wikimedia.org/wikipedia/commons/thumb/f/f0/H%C3%A4nsel_und_Gretel.jpg/512px-H%C3%A4nsel_und_Gretel.jpg

Stack trace: Example

$ ruby stack_trace_abbreviated.rb
Welcome to the to the todo list
Please enter your command:
quit
Goodbye!
Traceback (most recent call last):
  4: from stack_trace_abbreviated.rb:18:in `<main>'
  3: from stack_trace_abbreviated.rb:18:in `loop'
  2: from stack_trace_abbreviated.rb:21:in `block in <main>'
  1: from stack_trace_abbreviated.rb:8:in `execute_command'
stack_trace_abbreviated.rb:3:in `execute_quit_command': undefined local variable or method `ext' for main:Object (NameError)
Did you mean?  exit
               next
def execute_quit_command
  puts "Goodbye!"
  ext
end

def execute_command(command, todos)
  if command == "quit"
    execute_quit_command
  elsif command == "list"
    # ...
  end
end

puts "Welcome to the to the todo list"

todos = ["Buy milk", "Workout"]

loop do
  puts "Please enter your command:"
  command = gets.chomp
  execute_command(command, todos)
end
  4: from stack_trace_abbreviated.rb:18:in `<main>'
  3: from stack_trace_abbreviated.rb:18:in `loop'
  2: from stack_trace_abbreviated.rb:21:in `block in <main>'
  1: from stack_trace_abbreviated.rb:8:in `execute_command'
stack_trace_abbreviated.rb:3:in `execute_quit_command': undefined local variable or method `ext' for main:Object (NameError)

Action!

Let's do the interactive error message exercise.

What questions do you have?