ruby · level 2 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
catches an error so your program can carry on.
When something goes wrong while a program runs, Ruby raises an . Until now, that crashed the program. Wrap the risky lines between and end, and add rescue before the end. If an exception happens, Ruby jumps straight to the rescue lines instead of crashing.
Write rescue => error to catch the exception in a variable. error.message is the message you would have seen, and error.class is its name.
begin
puts "Opening the box..."
puts 10 / 0
puts "This line is skipped."
rescue => error
puts "Oops: #{error.message}"
end
puts "Still running!" Once an error happens, the rest of the lines inside begin are skipped.
guess first
Crash or carry on? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
begin
puts "Start"
puts nil.upcase
puts "Middle"
rescue => error
puts "Caught a #{error.class}"
end
puts "End"
your turn
Your turn. Share out the sweets.
Fill in how many sweets and how many friends, then press run. Try 0 friends as well and watch rescue step in.
fix it
The rescue never catches anything. Can you fix it?
- Read the error. Which line crashed, and is that line inside the
beginblock? rescueonly catches errors from the lines betweenbeginandrescue. Line 3 is outside them.- Move line 3 inside the
begin, after the line that says Sharing cookies.
nailed it
your program can survive a crash. :D
- Wrap risky lines in
begin…rescue…end. rescue => errorkeeps the exception in a variable.error.messagetells you what went wrong.
new words in your collection
- exception
- begin
- rescue
This lesson isn’t saved. A free account remembers every lesson you finish.