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.
Basic Structure
Section titled “Basic Structure”begin risky_methodrescue IOException => e puts e.messageelse puts "no error raised" # runs only when no exception is raisedensure cleanup # always runs, with or without an exceptionendThe 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 |
Multiple Rescue Clauses
Section titled “Multiple Rescue Clauses”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 blockendInline Rescue
Section titled “Inline Rescue”For simple fallbacks on a single expression:
value = risky_method rescue default_valueRaising Exceptions
Section titled “Raising Exceptions”raise "something went wrong" # raises RuntimeExceptionraise ParseException, "unexpected token at #{line}" # syntactic sugar for .new(message)raise ParseException.new("unexpected token at #{line}") # explicit formraise # re-raises current exceptionDefining Exceptions
Section titled “Defining Exceptions”class ParseException < Exception getter line: Int
def initialize(@line: Int, message: String) super.initialize(message) endend! Method Convention
Section titled “! Method Convention”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 failuredef save!: Void # raises SaveException on failure