How do you define a custom exception in Ruby, and why should you inherit from StandardError rather than Exception?
Last updated
Define one by subclassing
StandardError, often via an app-wide base error so callers can rescue broadly or narrowly. You can add custom data or a default message.A bare
rescueonly catchesStandardErrorand its descendants, so inheriting fromExceptionlets your error slip through.Exceptionalso coversSignalException,SystemExitandNoMemoryError. Catching at that level can swallow Ctrl-C and shutdown.
- https://blog.appsignal.com/2023/03/29/diving-into-custom-exceptions-in-ruby.html
- https://www.honeybadger.io/blog/ruby-exception-vs-standarderror-whats-the-difference/
- https://www.geeksforgeeks.org/ruby/ruby-exceptions/
- https://blog.appsignal.com/
- https://docs.ruby-lang.org/en/3.2/Exception.html
- https://docs.ruby-lang.org/en/3.4/exceptions_md.html
- https://reintech.io/blog/understanding-exception-handling-in-ruby
- https://franzejr.github.io/best-ruby/best_practices/using_exception_e.html