Skip to content

Rethrowing and uncaught errors

throw $e; inside a catch throws the same error again. The next try outside can catch it. An error that nothing catches ends the program with exit status 1.

Rethrowing

throw $e; inside a catch sends the same error on to the next handler.

The object does not change. Its message, its previous and its class stay as they were. Only location moves to the line of the rethrow, so a log line written later says where the error was sent on. Rethrow when the code you are in has something to do first, such as closing a file or counting a failure, and cannot handle the error itself.

Good to know: to add information of your own, do not rethrow. Throw a new error and give it the caught one as its cause, with { previous: $e }. A handler further out then has both messages.

The examples below show a plain rethrow, a rethrow after a log line, and a retry that gives up and sends the last error on.

Send the same error on

<?nvs
// Shows a plain rethrow. `throw $io;` inside the `catch` sends the same object
// on, so the handler further out reads the same message and the same class.
final class Relay
{
public static function go(): void
{
try {
throw new IOError('the socket closed');
} catch (IOError $io) {
echo "the relay saw it\n";
throw $io;
}
}
}
try {
Relay::go();
} catch (Throwable $sent) {
echo $sent->message, "\n";
// `location` is the line of the rethrow, which is line 13 here.
echo 'sent on at ', $sent->location, "\n";
}
Output
the relay saw it
the socket closed
sent on at docs/examples/lang/errors/rethrowing/01-send-the-same-error-on.nvs:13

Do something first

<?nvs
// Shows the common reason to rethrow. This code counts the failure and writes a
// line about it. It cannot decide what to do next, so it sends the error on.
final class Uploads
{
public static int $failures = 0;
public static function send(string $name): string
{
try {
if ($name == 'photo.raw') {
throw new IOError('the upload was cut off');
}
return 'sent ' . $name;
} catch (IOError $cut) {
Uploads::$failures = Uploads::$failures + 1;
echo 'upload ', $name, " failed\n";
throw $cut;
}
}
}
echo Uploads::send('notes.txt'), "\n";
try {
echo Uploads::send('photo.raw'), "\n";
} catch (IOError $failed) {
echo 'giving up: ', $failed->message, "\n";
}
echo 'failures so far: ', Uploads::$failures, "\n";
Output
sent notes.txt
upload photo.raw failed
giving up: the upload was cut off
failures so far: 1

A retry that gives up

<?nvs
// Shows a retry. The call is tried three times. The first two errors are caught
// and the loop tries again. The third one is sent on, because there is nothing
// left to try.
final class Payments
{
public static int $calls = 0;
public static function charge(int $order): string
{
Payments::$calls = Payments::$calls + 1;
throw new TimeoutError('the payment service did not answer');
}
public static function chargeWithRetries(int $order, int $tries): string
{
int $attempt = 1;
while ($attempt <= $tries) {
try {
return Payments::charge($order);
} catch (TimeoutError $slow) {
echo 'attempt ', $attempt, " timed out\n";
if ($attempt == $tries) {
// The last attempt sends the error on unchanged.
throw $slow;
}
}
$attempt = $attempt + 1;
}
return 'not reached';
}
}
try {
echo Payments::chargeWithRetries(4021, 3), "\n";
} catch (TimeoutError $gaveUp) {
echo 'gave up after ', Payments::$calls, ' calls: ', $gaveUp->message, "\n";
}
Output
attempt 1 timed out
attempt 2 timed out
attempt 3 timed out
gave up after 3 calls: the payment service did not answer

Details

throw $e; may also throw an error that was caught earlier and saved in a variable or a property. Each throw moves location to the line of that throw. The object stays the same, so == with the saved variable is true.

A clause that catches a wide class, such as catch (Throwable $e), does not change the class of the error. After throw $e;, a catch (TimeoutError $t) further out still catches a TimeoutError.

After a rethrow, backtrace still starts at the function that threw first. For the function that rethrew, the line in backtrace is the line of throw $e;.

The finally block of the try that rethrows runs before the error leaves that try.

When nothing catches the rethrown error, it ends the program like any uncaught throw. The report on the error output names the function that threw first.

An error that nothing catches

A throw that no catch handles ends your program.

The program stops at the line that threw. Everything it printed before that line is still printed. The exit status is 1. The error output gets a report with the error class, the message, and one line for each function the throw passed through, innermost first.

There is no global handler that catches everything for you and lets the program carry on. Catch the error where you can do something about it, or let it end the program.

Two methods let you watch this ending without changing it. Core\Fatal::onUncaughtThrow gives you the error itself. Core\Script::onExit runs at every ending, normal or not. Both run before the program exits, and the exit status is still 1.

The examples below show the plain ending first, then each of these two methods.

The program stops here

<?nvs
// Shows what happens when no `catch` handles a throw. The program ends at
// the line that threw, with exit status 1.
// proof: exit 1
class Repo
{
public static function get(int $id): string
{
throw new RuntimeError('no row ' . $id);
}
}
// This prints. Everything printed before the throw stays printed.
echo "loading order 7\n";
// Nothing catches this error, so the program ends here. The error output gets
// the class `RuntimeError`, the message, and one line for each function.
echo Repo::get(7), "\n";
// This line never runs.
echo "done\n";
Output
loading order 7

Print your own message

<?nvs
// Shows how to print your own message when an error ends the program.
// proof: exit 1
// This anonymous function runs when a throw reaches the top of the program and nothing
// caught it. The program still ends, and the exit status is still 1.
Core\Fatal::onUncaughtThrow(fn(Throwable $e): void => {
echo 'import stopped: ', $e->message, "\n";
echo "check your file, then run the import again\n";
});
class Import
{
public static function row(string $line): string
{
if (Core\Str::length($line) == 0) {
throw new RuntimeError('an empty line is not a row');
}
return $line;
}
}
echo Import::row('ada,lovelace'), "\n";
// The second row is empty, so this throw ends the program. The anonymous function above
// runs first and prints the two lines you wrote for your user.
echo Import::row(''), "\n";
Output
ada,lovelace
import stopped: an empty line is not a row
check your file, then run the import again

Write a summary at every ending

<?nvs
// Shows how to write a summary line even when an error ends the program.
// proof: exit 1
final class Counter
{
public static int $written = 0;
}
// This anonymous function runs at every ending: a normal one, an `exit`, and an error
// that nothing caught. `status()` is 1 for an ending an error caused.
Core\Script::onExit(fn(Core\Script\ExitReport $report): void => {
echo '--- rows written: ', Counter::$written, "\n";
echo '--- exit status: ', $report->status(), "\n";
echo '--- error: ', $report->error()?->message ?? 'none', "\n";
});
class Rows
{
public static function write(string $row): void
{
if (Core\Str::length($row) == 0) {
throw new RuntimeError('row ' . Counter::$written . ' is empty');
}
Counter::$written = Counter::$written + 1;
echo 'wrote ', $row, "\n";
}
}
Rows::write('ada,lovelace');
Rows::write('grace,hopper');
// This row is empty, so the program ends here. The summary above is still
// printed, and it reports the two rows that did get written.
Rows::write('');
Output
wrote ada,lovelace
wrote grace,hopper
--- rows written: 2
--- exit status: 1
--- error: row 2 is empty

Finally runs before the end

<?nvs
// Shows that `finally` still runs when nothing catches the error. The clean-up
// prints, and then the program ends with exit status 1.
// proof: exit 1
echo "start\n";
try {
throw new RuntimeError('the job failed');
} finally {
// This line runs before the program ends.
echo "clean-up done\n";
}
// This line never runs.
echo "after\n";
Output
start
clean-up done

Details

The report goes to the error output, and the normal output does not get it. By default the report is one line of JSON. msg is the message, fields.class is the error class, and nodes has one entry for each function with function, file and line. The last entry is <script>, the top level of the file.

With format = "text" in the [log] table of nvs.toml, the report is text. The first line is [error] and the message. The next line is the class. Then each function gets one line, such as #0 Repo::get() at main.nvs:4.

The report has the class of your own error, such as BadInput, when you throw one.

The report does not have the error in previous. To see the cause, catch the error and print $e->previous?->message yourself.

Before the program ends, every finally block that the error leaves still runs. What it prints stays in the normal output.

The exit status is 1 for every uncaught throw.

throw $e; does not add anything. To say more, throw a new error and pass the old one as { previous: $e }. See Error types.

  • Do rethrow when you only want to log the error and let a caller handle it.
  • Do throw a new error with { previous: $e } when you add information.
  • Don’t catch an error only to throw it again unchanged. Leave out the catch.
  • Don’t look for set_exception_handler. It does not exist.