Meet begin, rescue, raise and ensure — how Ruby lets a program stumble, clean up after itself and keep going instead of crashing.
The big picture
Programs stumble — plan for it
Files go missing, users type nonsense, nil sneaks in. Ruby turns disasters into catchable objects so your program can recover.
1
raise Throws
raise births an exception object describing what went wrong and stops the current method.
2
rescue Catches
A begin...rescue...end block guards code; rescue runs when an error appears inside.
3
ensure Always Runs
Cleanup code that must happen — closing files, printing farewells — belongs in ensure.
4
Errors Carry Info
Catch one as e and read e.message to tell the user what actually happened.
Programs stumble — plan for it
raise Throws1raise births an exception object describing what went wrong and stops the current method.
rescue Catches2A begin...rescue...end block guards code; rescue runs when an error appears inside.
ensure Always Runs3Cleanup code that must happen — closing files, printing farewells — belongs in ensure.
Errors Carry Info4Catch one as e and read e.message to tell the user what actually happened.
4 building blocks make up Programs stumble — plan for it
How it works
The life of an exception
Press Run and follow one raise from birth to recovery.
Watch it run
Watch an error get born and caught
check(5) sails through; check(-1) raises — and the rescue plus ensure team up to land the plane.
rescue_demo.rb
1defcheck(age)
2if age <0
3 raise "age cannot be negative"
4end
5"age is #{age}"
6end
7
8begin
9putscheck(5)
10putscheck(-1)
11puts"after the error"
12rescue=> e
13puts"Caught: #{e.message}"
14ensure
15puts"check complete"
16end
main
def check stores the method — notice the raise waiting patiently inside it.
Memory
no variables yet — press play
Console
output appears as the program runs…
Step 1/13
Visualize
What happens when things go wrong
Every raise travels this road: search for rescue, then clean up with ensure.
process decision input / output start / end
Challenge
Predict the output
A safe, a lock and one stubborn line that never runs.
vault.rb
1begin
2puts"open safe"
3 raise "locked!"
4puts"never runs"
5rescue=> e
6puts"alarm: #{e.message}"
7ensure
8puts"door closed"
9end
10puts"goodnight"
Your predicted output — one line per console line
Hint: raise stops the begin block instantly, so "never runs" never prints. rescue handles the error, ensure always runs, and only then does the program continue after end.
Recap
Key takeaways
Key takeaways5 takeaways
01
begin/rescue/end is the guarded zone — rescue catches errors raised inside.
02
raise births an exception; e.message tells you what went wrong.
03
ensure runs on every path: success, failure, even a re-raise.
04
Lines after a raise inside the same block are skipped entirely.
05
With no matching rescue anywhere, Ruby prints the trace and exits.