Control flow
die / try / CATCH
FullThrow with die, contain with try, and handle with a CATCH block.
die throws an exception, unwinding the call stack until something handles it. A try block contains that unwinding, and a CATCH block inside it decides what to do with whatever was thrown.
Throwing and catching #
CATCH sits inside the block whose exceptions it handles. Its default clause catches anything; the caught exception is the topic $_, with .message its text.
try {
die "boom";
CATCH {
default { say "caught: ", .message }
}
}
Output
caught: boomtry as an expression #
A try block with no CATCH swallows the exception and evaluates to Nil, and sets the error variable $!. Combined with // it gives a tidy fallback.
sub risky($x) {
die "negative" if $x < 0;
return $x * 2;
}
say risky(5);
say try { risky(-1) } // "failed";
Output
10
failedAfter a swallowed failure, $! holds the exception:
my $r = try { die "x" };
say $r.defined;
say $!.message;
Output
False
xNotes #
CATCHmatches withwhen/default(smartmatch), so you can branch on exception type or message — see Typed exceptions.- A
CATCHthat handles the exception lets the enclosing block continue past it, rather than propagating — the basis of resumable, per-iteration recovery. diewith a non-string argument throws that object directly;diewith a string wraps it in anX::AdHocexception whose.messageis that string.