Control flow

Typed exceptions

Full

Define your own Exception subclasses and dispatch on them in CATCH.

Exceptions are objects. Subclassing Exception gives you a named error type you can throw and then match precisely in a CATCH block — cleaner than inspecting message strings.

A custom exception #

Give the subclass a message method (its human-readable text) and throw an instance with .throw. CATCH then matches it by type with when.

class MyErr is Exception {
    method message { "custom error" }
}
try {
    MyErr.new.throw;
    CATCH {
        when MyErr { say "got MyErr" }
    }
}
Output
got MyErr

Matching by pattern #

Because CATCH uses smartmatch, you can also branch on the message with a regex, falling back to default.

try {
    die "specific";
    CATCH {
        when /specific/ { say "matched pattern" }
        default { say "other" }
    }
}
Output
matched pattern

Notes #