Explain the roles of begin, rescue, else, and ensure in Ruby exception handling.
Last updated
These keywords structure exception handling: begin marks the protected region, rescue handles raised errors, else runs only when no error occurred, and ensure always runs for cleanup.
begin: Opens the block whose code is monitored for exceptions (often implicit in a method/class body).rescue:Catches matching exceptions; you can specify a class and bind it:
rescue ArgumentError => e.Multiple
rescueclauses are tried top to bottom; most specific first.
else: Runs only if thebeginbody raised nothing; keeps the no-error path out of the protected region.ensure: Always executes (error or not, even onreturn): use for closing files, releasing locks, cleanup.
[lang:ruby]
begin
data = File.read(path)
rescue Errno::ENOENT => e
warn "missing: #{e.message}"
else
process(data) # only runs if read succeeded
ensure
log_attempt # always runs
end
- https://docs.ruby-lang.org/en/master/language/exceptions_md.html
- https://docs.ruby-lang.org/en/3.4/syntax/exceptions_rdoc.html
- https://reintech.io/blog/understanding-exception-handling-in-ruby
- https://blog.appsignal.com/2018/04/10/rescuing-exceptions-in-ruby.html
- https://blog.appsignal.com/2018/05/16/ensure-retry-and-reraise-exceptions-in-ruby.html
- https://blog.appsignal.com/2024/04/17/handling-exceptions-in-grape-for-ruby.html
- https://dev.to/sonianand11/ruby-interview-questions-part-1-44dp