midRuby

Explain Exception handling in Ruby using begin, rescue, ensure, and retry.

Updated May 17, 2026

Short answer

begin/rescue catches errors, ensure guarantees block execution regardless of errors, and retry reruns the begin block from the top.

Deep explanation

Ruby handles run-time errors using structured exceptions. Code prone to failures is wrapped in a begin block. If an error matching the rescue class occurs, execution shifts to the rescue block. The ensure block executes at the very end of the stack, whether an exception was raised, rescued, or left unhandled. retry can be invoked inside a rescue block to restart the entire execution flow from the first line of the begin block.

Real-world example

Wrapping HTTP requests or network connections in a retry block with an exponential backoff threshold, ensuring connections or files are always closed inside an ensure statement.

Common mistakes

  • Using a blanket `rescue Exception => e`. This catches critical low-level system errors like `NoMemoryError` and `SignalException` (like SIGTERM), preventing the application from shutting down or killing stuck tasks cleanly. Always rescue `StandardError` or lower.

Follow-up questions

  • What is the default exception class rescued if none is specified?
  • How do you re-raise the current active exception inside a rescue block?

More Ruby interview questions

View all →