Ruby exceptions: Difference between revisions
From wikinotes
(→basics) |
|||
Line 28: | Line 28: | ||
</blockquote><!-- standarderrror --> | </blockquote><!-- standarderrror --> | ||
= raise/throw = | = raise/throw/create = | ||
<blockquote> | <blockquote> | ||
<source lang="ruby"> | <source lang="ruby"> | ||
Line 34: | Line 34: | ||
raise(ArgumentError, 'bad data') # ArgumentError | raise(ArgumentError, 'bad data') # ArgumentError | ||
raise(ArgumentError, 'bad data') unless x == 1 # raise... unless... | raise(ArgumentError, 'bad data') unless x == 1 # raise... unless... | ||
# manually create and assign backtrace | |||
exception = StandardError.new("message") | |||
exception.set_backtrace(caller) | |||
</source> | </source> | ||
</blockquote><!-- throwing excepts --> | </blockquote><!-- throwing excepts --> |
Latest revision as of 15:28, 31 October 2023
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/create
raise 'bad data' # StandardError raise(ArgumentError, 'bad data') # ArgumentError raise(ArgumentError, 'bad data') unless x == 1 # raise... unless... # manually create and assign backtrace exception = StandardError.new("message") exception.set_backtrace(caller)
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() endretry
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