An interactive Ruby lesson
Exceptions
An exception interrupts normal execution when something goes wrong. Use raise to signal an error and rescue to handle an error you expect. Start with Methods and Conditions.
p displays an inspected value, including quotes around strings. Predict the output, press Run, then open the expected output. Change one input and run again. Reset restores that example; Stop ends a running example.
The first Run downloads Ruby into your browser. JavaScript and a network connection are needed to run examples. Each run starts fresh, so keep the method definition and its calls together in the editor you run. The code and answers remain readable without JavaScript.
1. Raise an error
raise ArgumentError, "Invalid input" raises an exception of class ArgumentError. The text after the comma becomes its message. begin starts the section; end closes it. The rescue ArgumentError line handles that class and its subclasses. Here it displays a fixed response. Predict the output.
Show expected output
"Invalid input"
Try it: Change the response in p("Invalid input") to p("Try again"). Predict the output. The response is separate from the error message.
2. Follow the rescue path
When raise runs, Ruby skips the remaining statements in that begin section. The matching rescue runs, then execution continues after end. Predict which lines appear and which line is skipped.
Show expected output
"checking" "handled" "finished"
Try it: Replace the raise line with # no error this time, a comment. Predict which line appears in place of "handled".
3. Read the error message
rescue ArgumentError => error assigns the rescued exception to error. Read its class with error.class and its message with error.message. The message is the text supplied to raise. Predict both lines.
Show expected output
ArgumentError "quantity must be positive"
Try it: Change the text supplied to raise to "use a positive number". Predict which output line changes.
A rescue names the class it can handle. rescue ArgumentError does not handle an unrelated class such as TypeError. If no matching rescue is found as the error travels through its callers, the program stops. Handle errors where your program has a useful response.
4. Check an input
Use a condition to raise an error only for an invalid quantity. Here a valid quantity must be greater than zero. A valid input reaches the calculation and skips the rescue section. Predict the output for quantity = 2.
Show expected output
6
Try it: Change quantity = 2 to quantity = 0, then to quantity = -1. Predict each result. Try quantity = 1 and explain why the calculation runs.
5. Handle a method call
The total method checks its argument and raises ArgumentError for zero or a negative number. When it raises, it stops before returning a calculation. The caller surrounds the call with begin and handles the error. Predict the output.
Show expected output
"quantity must be positive" "finished"
Try it: Change total(0) to total(2), then to total(-2). Predict each result. Explain why the caller can handle an error raised inside the method.
6. Run a final step with ensure
ensure runs after the normal code or the rescue section. This example uses it to display that the check is complete. Predict the order of the three output lines.
Show expected output
"quantity must be positive" "check complete" "finished"
Try it: Change quantity = 0 to quantity = 2, then to quantity = -1. Predict the output order. Explain why "check complete" appears on both paths.
ensure also runs when an error has no matching rescue. It does not handle that error; the error continues to the caller. Code after end runs here because the error was handled.
Practice on your own
Replace the code in the last editor with a program for these tasks. Predict the output, then run it.
- Define
ticket_total(quantity). RaiseArgumentErrorwith the message"quantity must be positive"when the quantity is zero or negative. Otherwise, returnquantity * 4. - Call
p(ticket_total(0))insidebegin. RescueArgumentError => errorand displayerror.messagewithp. - Add
ensureto display"order checked". Afterend, display"finished". - Explain which code is skipped after the error and why the final two messages still appear.
Show one solution and its output
def ticket_total(quantity)
if quantity <= 0
raise ArgumentError, "quantity must be positive"
end
quantity * 4
end
begin
p(ticket_total(0))
rescue ArgumentError => error
p(error.message)
ensure
p("order checked")
end
p("finished")Output:
"quantity must be positive" "order checked" "finished"
Change ticket_total(0) to ticket_total(3), then to ticket_total(-1). Predict each output and explain which section runs.
Ruby documentation
See the Ruby 4.0 documentation for exception handling, specific rescue classes, and ensure. The raise method documentation explains how the class and message arguments set the error's details.
Return to the Ruby skill tree to choose more practice.