Skip to content

Error Handling

Amethyst uses Ruby’s raise/rescue/else/ensure model, backed by .NET exceptions. All exception classes inherit from System.Exception and follow .NET naming conventions — ending in Exception.

begin
risky_method
rescue IOException => e
puts e.message
else
puts "no error raised" # runs only when no exception is raised
ensure
cleanup # always runs, with or without an exception
end

The four clauses in order:

Clause When it runs
begin Always
rescue When a matching exception is raised
else When no exception is raised
ensure Always, after everything else
begin
parse_file(path)
rescue FileNotFoundException => e
log "file not found: #{e.message}"
rescue ParseException => e
log "parse error: #{e.message}"
retry # retry the begin block
end

For simple fallbacks on a single expression:

value = risky_method rescue default_value
raise "something went wrong" # raises RuntimeException
raise ParseException, "unexpected token at #{line}" # syntactic sugar for .new(message)
raise ParseException.new("unexpected token at #{line}") # explicit form
raise # re-raises current exception
class ParseException < Exception
getter line: Int
def initialize(@line: Int, message: String)
super.initialize(message)
end
end

Methods ending in ! either raise on failure or change their receiver in place. For the raising kind, the non-! variant returns nil or false instead. In C#, the pair compiles as TrySave and Save (see .NET Naming Interop):

def save: Bool # returns false on failure
def save!: Void # raises SaveException on failure