Control flow

die / try / CATCH

Full

Throw 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: boom

try 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
failed

After a swallowed failure, $! holds the exception:

my $r = try { die "x" };
say $r.defined;
say $!.message;
Output
False
x

Notes #