Exception Handling

Lesson 12 of 20

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.

raise Throws

raise births an exception object describing what went wrong and stops the current method.

rescue Catches

A begin...rescue...end block guards code; rescue runs when an error appears inside.

ensure Always Runs

Cleanup code that must happen — closing files, printing farewells — belongs in ensure.

Errors Carry Info

Catch one as e and read e.message to tell the user what actually happened.