Ruby exceptions

From wikinotes
Revision as of 19:39, 29 July 2021 by Will (talk | contribs) (→‎basics)

Documentaiton

exception docs https://docs.ruby-lang.org/en/master/Exception.html#class-Exception-label-Built-In+Exception+Classes
builtin exceptions https://ruby-doc.org/core-2.5.1/Exception.html

Basics

  • Only StandardError and subclasses interrupt execution (this is the default exception)
begin                    # try

rescue                   # except
rescue Exception => exc  # except Exception as exc

retry                    # retry the entire begin/rescue block

ensure                   # finally

$!                       # last raised exception
raise $!                 # re-raise exception

raise/throw

raise 'bad data'                      # StandardError
raise(ArgumentError, 'bad data')      # ArgumentError
raise(ArgumentError, 'bad data') unless x == 1  # raise... unless...

rescue/catch/except

basics

op_file = File.open(op_name, "w")
begin  # try
  while data = socket.read(512)
    opFile.write(data)
  end

rescue SystemCallError
  puts $!   # '$!' holds last raised exception
  raise $!  # re-raise last exception

rescue SyntaxError, NameError => exc
  puts exc
  raise exc

resuce => exc
  raise exc  # catch any exception

ensure
  data.close()

end

retry

If you can identify/correct the cause of an exception, you can retry the entire try/except clause.

# TODO!!
begin
rescue

Custom Exceptions

ruby encourages defining a generic exception for your library, that all specific namespaces inherit from.
:: in front of StandardError is not necessary, but it avoids scope conflicts.

class MyError < ::StandardError
end