catch as an expression
Repo::get($id) catch (IOError $e) => 0 returns the result of Repo::get($id). If that call
throws an IOError, the result is 0. It is the short form of a try block that only needs a value.
catch after an expression
catch written after an expression gives that expression a value to fall back on when it throws an error. It saves writing a whole try block for one value.
Write the expression, then catch (SomeError $e) => fallback. If the expression runs normally, its own value is the result. If it throws an error the arm matches, the arm's value is the result. You may write several arms after one expression; they are tried in order, and the first class that matches wins. An error no arm matches keeps travelling, as it would without the catch. An arm holds an expression, so throw is allowed there and return is not.
Good to know: catch (Throwable) => value with no variable and no throw gives a warning. It hides every error, including the ones you never thought about.
The examples below show a fallback for a row that is missing, then several arms tried in order, then a report line whose division is guarded and a low-level error replaced by a clear one. The last two show the type of the result, and a return in an arm that does not compile.
A fallback when a row is missing
<?nvs// Shows how a `catch` arm after an expression supplies a fallback value.// `Repo::price` throws when it has no row for a product.
class Repo{ public static function price(string $sku): int { if ($sku == 'lamp') { return 1200; } throw new IOError('no row for ' . $sku); }}
// The lookup worked, so the result is the call's own value. This prints 1200.echo Repo::price('lamp') catch (IOError $missing) => 0, "\n";
// The lookup threw, so the result is the arm's value. This prints 0.echo Repo::price('ring') catch (IOError $missing) => 0, "\n";
// The arm can read the error it caught. This prints `no row for ring`.echo Repo::price('ring') catch (IOError $e) => $e->message, "\n";12000no row for ringSeveral arms tried in order
<?nvs// Shows several arms written after one expression. They are tried in order and// the first class that matches wins. The arms belong to the expression on the// left, not to each other.
class Field{ public static function toAmount(string $text): int { if ($text == '') { throw new LogicError('the field is empty'); } if ($text == '?') { throw new IOError('the field is unreadable'); } return 42; }}
// Nothing threw, so the result is the call's own value. This prints 42.echo Field::toAmount('42') catch (LogicError $l) => -1 catch (IOError $io) => -2, "\n";
// The first arm matches. This prints -1.echo Field::toAmount('') catch (LogicError $l) => -1 catch (IOError $io) => -2, "\n";
// The second arm matches. This prints -2.echo Field::toAmount('?') catch (LogicError $l) => -1 catch (IOError $io) => -2, "\n";
// An error no arm matches keeps travelling, so the `try` around it catches it.try { echo Field::toAmount('') catch (IOError $io) => -2, "\n";} catch (LogicError $left) { echo 'left the expression: ', $left->message, "\n";}42-1-2left the expression: the field is emptyA report line that survives an empty row
<?nvs// A report page shows an average for every row, and a price list turns a// missing rate into a clear error. `catch` binds looser than the arithmetic,// so the guard covers the whole division.
class Report{ public static function line(string $label, int $total, int $count): string { // A row with no entries would stop the page with an error. The arm // supplies 0 instead. var $average = $total / $count catch (ArithmeticError $zero) => 0; return $label . ': ' . $average as string; }}
class Rates{ public static function read(string $code): int { throw new IOError('no rate for ' . $code); }
// An arm may throw instead of giving a value. The caller then sees an error // that says what went wrong at this level. public static function forCode(string $code): int { return Rates::read($code) catch (IOError $e) => throw new RuntimeError('price list is incomplete: ' . $e->message); }}
// This prints `north: 300`, then `south: 0`, then `east: 0`.echo Report::line('north', 900, 3), "\n";echo Report::line('south', 120, 0), "\n";echo Report::line('east', 0, 7), "\n";
try { echo Rates::forCode('EUR'), "\n";} catch (RuntimeError $stopped) { echo $stopped->message, "\n";}north: 300south: 0east: 0price list is incomplete: no rate for EURThe result type includes every arm
<?nvs// Shows that the type of the result includes the type of every arm.
class Repo{ public static function get(int $id): int { if ($id < 0) { throw new IOError('no such row'); } return $id * 2; }}
// `get` returns `int` and the arm gives `null`, so the result is `?int`.?int $found = Repo::get(-1) catch (IOError) => null;// This prints `none`.echo $found ?? 'none', "\n";
// One arm gives a string and the other gives an int, so the variable is `mixed`.// The second arm matches. This prints -1.mixed $either = Repo::get(-1) catch (LogicError $logic) => 'logic' catch (IOError $io) => -1;echo $either, "\n";none-1An arm cannot return
<?nvs// Shows that an arm is an expression, so `return` is not allowed there.// Write a `try` block when you need a statement. This program does not compile.// proof: compile-error
class Repo { public static function get(int $id): int { return $id; }}
int $n = Repo::get(1) catch (IOError $e) => return 0;echo $n, "\n";error[E0126]: a `catch` arm is an expression, and `return` is a statement --> 05-an-arm-cannot-return.nvs:12:45 |12 | int $n = Repo::get(1) catch (IOError $e) => return 0; | ^^^^^^ `return` cannot appear here = help: `throw` is an expression, so `catch (E $e) => throw new …` is allowed here; for an early return write the block form, `try { … } catch (E $e) { return …; }`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
Every arm checks the error that the expression on the left threw. In f() catch (LogicError $a) => x catch (IOError $b) => y, the IOError arm does not check x.
An arm for a parent class that is written before an arm for its subclass matches first. The later arm never runs. This compiles without a warning.
catch covers everything to its left up to an assignment. In $x = $a / $b catch (ArithmeticError $e) => 0, it covers the whole division. It also covers a whole ?: and a whole ?? chain.
The variable is optional: catch (IOError) => 0 is allowed. An arm names one class. catch (IOError | LogicError $e) does not compile: it is the error E0245.
An arm's variable can only be used inside that arm. After the arm, you may declare the same name again. The name must not already be a variable of the function when the arm starts: that is the error E0406.
The type of the result includes the type of the expression and the type of every arm. If get returns int and an arm gives null, the result is ?int. Writing that result into an int variable does not compile: it is the error E0401. An arm that throws adds nothing to the type.
return, break and continue in an arm do not compile: that is the error E0126.
This form has no finally. When the error leaves the expression, the finally block of the try around it runs as usual.
The warning for catch (Throwable) => value is W1006. An arm with a variable does not get it.
Use this when you need statements
Section titled “Use this when you need statements”Write a try block when the error needs more than one value: a log line, a cleanup step, or a
return. See throw, try and catch.
Do and don’t
Section titled “Do and don’t”- Do name the class you expect:
catch (IOError $e) => 0. - Do use this form for a default value, such as
0ornull. - Don’t write
catch (Throwable) => value. It hides every error, also the bugs. The compiler warns about it. - Don’t put a
returnin an arm. Use thetryblock.
