Tutorial by Examples

To raise an exception use Kernel#raise passing the exception class and/or message: raise StandardError # raises a StandardError.new raise StandardError, "An error" # raises a StandardError.new("An error") You can also simply pass an error message. In this case, the message i...
A custom exception is any class that extends Exception or a subclass of Exception. In general, you should always extend StandardError or a descendant. The Exception family are usually for virtual-machine or system errors, rescuing them can prevent a forced interruption from working as expected. # ...
Use the begin/rescue block to catch (rescue) an exception and handle it: begin # an execution that may fail rescue # something to execute in case of failure end A rescue clause is analogous to a catch block in a curly brace language like C# or Java. A bare rescue like this rescues Stand...
You can handle multiple errors in the same rescue declaration: begin # an execution that may fail rescue FirstError, SecondError => e # do something if a FirstError or SecondError occurs end You can also add multiple rescue declarations: begin # an execution that may fail rescue ...
It may be helpful to include additional information with an exception, e.g. for logging purposes or to allow conditional handling when the exception is caught: class CustomError < StandardError attr_reader :safe_to_retry def initialize(safe_to_retry = false, message = 'Something went wro...

Page 1 of 1