Control flow
Typed exceptions
FullDefine 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 MyErrMatching 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 patternNotes #
when SomeTypeworks because smartmatch against a type tests membership; add attributes to the exception class to carry structured data alongside the message.- List several
whenclauses to handle different exception types distinctly, with a finaldefaultfor the rest. - Built-in errors are already typed (
X::TypeCheck,X::AdHoc, …), so real handlers can catch, say, onlyX::IOand let everything else propagate.