Skip to content

throw, try and catch

throw new IOError("...") stops the current function and throws an error. try { ... } runs a block, and a catch (IOError $e) { ... } after it runs when that block throws an IOError. finally { ... } runs last, whatever happened.

throw

throw reports an error and stops the work in progress. It takes an object of a class under Throwable, such as LogicError, IOError, or a class you wrote yourself. The nearest catch clause whose class matches takes over, and the lines after the throw never run.

throw new RuntimeError("the reason"); is the usual form. The message is the first argument, and a class may add more. If no catch matches, the program ends with status 1.

throw is a statement, and it is also an expression. You can write it where a value is expected: after ?? when a value may be missing, in the default arm of a match, and in a ternary arm. In each of those places the program either has a value or throws, so every line after it can use the value.

The examples below show throw after ?? for a missing field, in the default arm of a match over order statuses, and in the checks a program runs before it ships an order. The last one shows a method that throws for a value it cannot use, and a catch around the call.

A value that may be missing

<?nvs
// Shows `throw` written after `??`. The value on the left is used when it is
// there. When it is missing, the `throw` on the right stops the method with an
// error.
final class Rows
{
public static function email(array<string> $row): string
{
// `??` gives the value stored under `"email"`. If the row has no such
// key, `throw` raises a `LogicError` and the method returns nothing.
return $row['email'] ?? throw new LogicError('the row has no email');
}
}
array<string> $complete = ['id' => '7', 'email' => 'ada@example.com'];
array<string> $partial = ['id' => '8'];
// This prints ada@example.com.
echo Rows::email($complete), "\n";
try {
echo Rows::email($partial), "\n";
} catch (LogicError $missing) {
// This prints "the row has no email".
echo $missing->message, "\n";
}
Output
ada@example.com
the row has no email

A status the program does not know

<?nvs
// Shows `throw` in a `match` arm. Every status the program knows has an arm of
// its own. An unknown status reaches the `default` arm, and that arm throws.
final class Orders
{
public static function nextStep(string $status): string
{
return match ($status) {
'paid' => 'pack the order',
'packed' => 'print the label',
'shipped' => 'nothing left to do',
// A `match` arm may be a `throw`. The method then returns nothing
// for this subject, and the caller gets the error.
default => throw new LogicError('unknown order status: ' . $status),
};
}
}
array<string> $statuses = ['paid', 'packed', 'returned'];
// The first two lines print a step. The third prints the error message,
// because "returned" has no arm.
foreach ($statuses as string $status) {
try {
string $step = Orders::nextStep($status);
echo $status, ': ', $step, "\n";
} catch (LogicError $unknown) {
echo $status, ': ', $unknown->message, "\n";
}
}
Output
paid: pack the order
packed: print the label
returned: unknown order status: returned

Checking an order before it ships

<?nvs
// Shows the checks a program runs before it ships an order. Each check either
// gives a value or throws, so the last line can use both values.
final class Shipment
{
public static function forOrder(int $quantity, ?string $address): string
{
// The ternary gives `$quantity` when it is positive. For 0 it throws.
int $items = $quantity > 0
? $quantity
: throw new LogicError('an order needs at least one item');
// `??` covers the second case: an address nobody filled in.
string $to = $address ?? throw new LogicError('an order needs an address');
return 'ship ' . $items . ' item(s) to ' . $to;
}
}
// This prints: ship 3 item(s) to 12 Baker Street
echo Shipment::forOrder(3, '12 Baker Street'), "\n";
try {
echo Shipment::forOrder(0, '12 Baker Street'), "\n";
} catch (LogicError $empty) {
echo $empty->message, "\n";
}
try {
echo Shipment::forOrder(2, null), "\n";
} catch (LogicError $nowhere) {
echo $nowhere->message, "\n";
}
Output
ship 3 item(s) to 12 Baker Street
an order needs at least one item
an order needs an address

Reporting a value the method cannot use

<?nvs
// Shows how `throw` reports a value a method cannot work with. The method
// stops at the `throw`, and the `catch` around the call runs instead.
class Age
{
public static function of(int $birthYear, int $thisYear): int
{
if ($birthYear > $thisYear) {
throw new RuntimeError('a birth year in the future: ' . $birthYear);
}
return $thisYear - $birthYear;
}
}
// This prints 41
echo Age::of(1985, 2026), "\n";
try {
echo Age::of(2040, 2026), "\n";
echo "this line is never reached\n";
} catch (RuntimeError $e) {
// This prints: cannot use that row: a birth year in the future: 2040
echo 'cannot use that row: ', $e->message, "\n";
}
Output
41
cannot use that row: a birth year in the future: 2040

Details

throw "x", throw 5 and throw new Foo() for a class not under Throwable are each the error E0780. A variable whose type is an interface is E0780 too, even when the object in it extends RuntimeError.

A ?LogicError variable may be thrown. When it is null, the throw throws a LogicError with the message Can only throw objects. A mixed variable may be thrown as well. When its value is not a Throwable, the result is the same LogicError.

throw as a value can stand after ?? and ?:, in a match arm, in either arm of a ternary, after ||, and after echo. Its type is never. At a typed variable or a method argument, int $x = throw …; is the error E0401. In arithmetic such as 1 + throw …, the result is mixed.

A method whose return type is int may end with a throw and no return. A method may also have the return type never and always throw.

throw LogicError("x") without new is the error E0320.

The classes you can throw are on the page Error types.

try, catch and finally

try guards a block of code that can throw. Write try { … }, then catch clauses, a finally block, or both. Each catch clause names one class from the throwable tree.

A clause matches its own class and every class under it, so catch (RuntimeError $e) also takes an IOError. The clauses are tried from top to bottom, so the narrow classes go first. You may leave the variable out when you do not need the error itself.

finally runs on every way out of the block: after the body, after a catch, and on return, break, continue or an error that nothing caught.

The examples below show two clauses picked by class, a catch that throws a new error with a cause, and the clean-up around a job that reads rows. Then they show a loop that carries on after a row that fails, two clauses with one variable name, which does not compile, and a finally that runs on continue.

Two clauses picked by class

<?nvs
// Shows two `catch` clauses in the order they are tried. `TimeoutError` is a
// kind of `RuntimeError`, so the narrow clause is written first. A
// `RuntimeError` clause written first would take both errors.
final class Feed
{
public static function read(string $name): string
{
if ($name == 'slow') {
throw new TimeoutError('the feed did not answer');
}
if ($name == 'gone') {
throw new RuntimeError('the feed is not there');
}
return '3 rows';
}
}
array<string> $names = ['daily', 'slow', 'gone'];
foreach ($names as string $name) {
try {
string $rows = Feed::read($name);
echo $name, ': ', $rows, "\n";
} catch (TimeoutError $slow) {
echo $name, ': timed out, ', $slow->message, "\n";
} catch (RuntimeError $other) {
echo $name, ': failed, ', $other->message, "\n";
}
}
Output
daily: 3 rows
slow: timed out, the feed did not answer
gone: failed, the feed is not there

A catch that reports its own error

<?nvs
// Shows a `catch` that cannot handle what it caught. It throws an error of its
// own and gives the caught one as the cause. That new error leaves the `try` it
// was thrown in, and the caller handles it.
final class Settings
{
public static function port(array<string> $raw): int
{
try {
return $raw['port'] as int;
} catch (RuntimeError $unusable) {
throw new LogicError('the port setting is unusable', { previous: $unusable });
}
}
}
array<string> $withoutPort = ['host' => 'localhost'];
array<string> $withText = ['port' => 'eight'];
try {
echo Settings::port($withoutPort), "\n";
} catch (LogicError $first) {
echo $first->message, "\n";
// The cause says what the inner error was.
echo 'caused by: ', $first->previous?->message ?? 'nothing', "\n";
}
try {
echo Settings::port($withText), "\n";
} catch (LogicError $second) {
echo $second->message, "\n";
echo 'caused by: ', $second->previous?->message ?? 'nothing', "\n";
}
Output
the port setting is unusable
caused by: undefined array key `port`
the port setting is unusable
caused by: cannot convert a `string` of 5 bytes to `int`

Cleaning up around every row

<?nvs
// Shows the clean-up a program runs around a job that reads rows. Every row has
// a `finally` of its own, and the whole job has one around it. The inner block
// runs first.
final class Import
{
public static int $rowsClosed = 0;
public static int $jobsClosed = 0;
public static function rows(array<string> $lines): int
{
try {
int $total = 0;
foreach ($lines as string $line) {
try {
if ($line == '') {
throw new RuntimeError('an empty row stopped the job');
}
$total = $total + 1;
} finally {
Import::$rowsClosed = Import::$rowsClosed + 1;
}
}
return $total;
} finally {
Import::$jobsClosed = Import::$jobsClosed + 1;
}
}
}
array<string> $complete = ['a', 'b', 'c'];
array<string> $withHole = ['a', '', 'c'];
// This prints 3.
echo Import::rows($complete), "\n";
try {
echo Import::rows($withHole), "\n";
} catch (RuntimeError $stopped) {
echo $stopped->message, "\n";
}
// The failed job closed its row and then itself, so both counts went up.
echo 'rows closed: ', Import::$rowsClosed, "\n";
echo 'jobs closed: ', Import::$jobsClosed, "\n";
Output
3
an empty row stopped the job
rows closed: 5
jobs closed: 2

Finally runs before the caller gets the value

<?nvs
// Shows when `finally` runs for a function that returns. It runs before the
// caller gets the value, so "checked" prints first.
final class Loader
{
public static int $reads = 0;
public static function load(string $key): string
{
try {
if ($key == 'bad') {
throw new IOError('cannot read ' . $key);
}
return 'value-of-' . $key;
} finally {
Loader::$reads = Loader::$reads + 1;
echo 'checked ', $key, "\n";
}
}
}
echo Loader::load('host'), "\n";
// The `IOError` passes the `LogicError` clause. The second clause catches it.
try {
echo Loader::load('bad'), "\n";
} catch (LogicError $wrongClause) {
echo "not this one\n";
} catch (IOError $io) {
echo 'io: ', $io->message, "\n";
}
// The `finally` block ran for both calls, so this prints 2.
echo 'reads: ', Loader::$reads, "\n";
Output
checked host
value-of-host
checked bad
io: cannot read bad
reads: 2

A return in finally does not compile

<?nvs
// Shows a `return` inside `finally`. It does not compile, because it would
// replace the value of the `try` and any error that is leaving the block.
// proof: compile-error
final class Counter {
public static function next(int $n): int {
try {
return $n + 1;
} finally {
return 0;
}
}
}
echo Counter::next(1), "\n";
Output
error[E0250]: a `return` never leaves a `finally` block
--> 05-a-return-in-finally-does-not-compile.nvs:11:13
|
11 | return 0;
| ^^^^^^^^^ this discards what the region was leaving with
= help: return from the `try` or a `catch` to change the result, or write it after the whole region
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Carrying on after a row that fails

<?nvs
// Shows the block form of `try`. The `catch` clause runs when the code inside
// the `try` block throws an error, and the program carries on after the block.
class Amount
{
public static function of(string $text): int
{
?int $value = $text as ?int;
if ($value == null) {
throw new RuntimeError('not a whole number: ' . $text);
}
return $value;
}
}
array<string> $rows = ['12', 'seven', '30'];
int $total = 0;
foreach ($rows as string $row) {
try {
$total = $total + Amount::of($row);
} catch (RuntimeError $e) {
// This prints: skipped: not a whole number: seven
echo 'skipped: ', $e->message, "\n";
}
}
// This prints 42. The row that failed added nothing.
echo $total, "\n";
Output
skipped: not a whole number: seven
42

Two clauses need two names

<?nvs
// Shows that two `catch` clauses for different types need two variable names.
// Both clauses below use `$e`, so this program does not compile.
// proof: compile-error
class Twice
{
public static function run(): string
{
try {
throw new LogicError('x');
} catch (LogicError $e) {
return 'a';
} catch (Throwable $e) {
return 'b';
}
}
}
echo Twice::run(), "\n";
Output
error[E0406]: `$e` is already declared
--> 07-two-clauses-need-two-names.nvs:12:29
|
12 | } catch (LogicError $e) {
| -- first declared here
...
14 | } catch (Throwable $e) {
| ^^ second declaration
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Finally runs on continue

<?nvs
// Shows that `finally` also runs when `continue` leaves the `try` block.
int $i = 0;
while ($i < 3) {
$i++;
try {
if ($i == 2) {
// The rest of the block is skipped, but `finally` still runs.
continue;
}
echo 'body', $i, ' ';
} finally {
echo 'fin', $i, ' ';
}
}
// The loop above prints: body1 fin1 fin2 body3 fin3
// The second pass prints only fin2.
echo "\n";
Output
body1 fin1 fin2 body3 fin3

Details

A try needs at least one catch clause or a finally block. A try with neither does not compile: it is the error E0242.

A catch clause may name an interface. It then matches every class that implements that interface.

A clause for a parent class that is written before a clause for its subclass catches that error first. The later clause never runs. This compiles without a warning.

catch (LogicError | IOError $e) does not compile: it is the error E0245. Write two clauses.

The variable of a catch clause is a variable of the whole function. Two clauses in one function may use the same name when they catch the same type. When the types are different, the second clause does not compile: that is the error E0406.

A catch clause may throw as well. The other clauses of the same try do not catch the new error. The finally block of that try runs first, and then the next try outside handles the error. This is how one layer reports an error of its own and keeps the caught one as its previous.

When one try is inside another, the inner finally block runs before the outer one.

A return inside a finally block does not compile: it is the error E0250. Change the result in the try or in a catch, or after the whole block.

A break or continue that would leave a finally block does not compile: it is the error E0251. This is also true for break 2 from a loop inside the finally. A loop that is written completely inside the finally block may use break and continue.

A yield inside a finally block does not compile: it is the error E0255. A generator cannot pause there. Write the yield in the try block or after the whole block.

A finally block may contain its own try and catch. An error caught there does not leave the block.

When the try returns a value, the value is computed first. The finally block runs after that, so a change it makes does not change the value that the function returns.

When no catch handles an error, the finally blocks still run. Then the error leaves the function, or ends the program at the top level.

A finally block can throw while an error is leaving the block. The handler outside then gets the new error, and its previous is the first error. A method called in the finally that throws does the same. If the new error already has a previous, it keeps that previous, and the first error is lost.

A try block is the long form. When you only want a fallback value, write catch as an expression: catch as an expression.

  • Do put the narrow classes first. A catch (Throwable $e) first catches everything.
  • Do catch the class you expect, such as IOError. Then a bug still shows as an error.
  • Do use finally to close or clean up something, whatever happens in the try.
  • Don’t use return in finally. It does not compile.
  • Don’t write Exception. It does not exist. Use RuntimeError, LogicError or Throwable.