Languagethrows and nothrow

Language

throws and nothrow

The throws and nothrow clauses state what a function lets escape; they compile to @throws tags and the checker verifies them against the body.

throws A|B after a signature names the exceptions a function or method lets escape, and nothrow says that it lets none escape. They are what a @throws tag says in a PHPStan docblock, written in the signature: the checker verifies them against the body, and the compiled PHP carries them as @throws tags. They are not Java's checked exceptions: a caller does not have to catch or redeclare anything.

At a glance

you write
namespace App;

final class InsufficientFunds extends \DomainException {}

final class Account
{
    private int $balance = 0;

    balance(): int nothrow => $this->balance;

    /** Takes money out, never below zero. */
    withdraw(int $amount): void throws InsufficientFunds {
        if ($amount > $this->balance) {
            throw new InsufficientFunds("cannot withdraw $amount");
        }
        $this->balance -= $amount;
    }
}
phn build writes
<?php

/* @generated by phaenon from Example.phn */

declare(strict_types=1);

namespace App;

final class InsufficientFunds extends \DomainException {}

final class Account
{
    private int $balance = 0;

    /**
     * @throws void
     */
    public function balance(): int
    {
        return $this->balance;
    }

    /**
     * Takes money out, never below zero.
     * @throws InsufficientFunds
     */
    public function withdraw(int $amount): void
    {
        if ($amount > $this->balance) {
            throw new InsufficientFunds("cannot withdraw $amount");
        }
        $this->balance -= $amount;
    }
}

throws

The clause follows the return type, or the parameter list when there is no return type, and comes before the body, the arrow or the ;. It names a class or a union written as in a catch, throws NotFound|Conflict. Each member must be a Throwable, or a type parameter bounded by one (P2319).

It means what the @throws tag means: documentation that the checker reads and holds to the body.

  • A member the body never throws is a warning, P2404, on a function and on a method nobody can override (private, final, or in a final class). An overridable method keeps the member without a finding, because its clause is the contract its overrides may use.
  • An exception the body throws but does not declare is not reported. The clause is not a complete list, and no exception class is treated as "checked".
  • A catch that nothing in its try block can throw is a warning, P2403: the checker knows what each call declares.

The clause is for named functions and methods. A closure keeps a @throws docblock tag.

nothrow

nothrow stands where throws would, and says that nothing escapes. It is the clause spelling of PHPStan's @throws void, and compiles to that tag.

you write
namespace App;

function ratio(int $part, int $whole): int nothrow => intdiv($part * 100, $whole) + $part % $whole;
$ phn checkexit 1
src/Example.phn:3:85: error P2405: function App\ratio() declares nothrow but throws DivisionByZeroError here
    3 | function ratio(int $part, int $whole): int nothrow => intdiv($part * 100, $whole) + $part % $whole;
      |                                                                                     ^^^^^^^^^^^^^^
1 files checked: 1 errors, 0 warnings

What it promises is checked against the throw points the checker can name:

  • a throw, a call to a function that declares what it throws, a / or % whose divisor may be zero, and a match without default that is not exhaustive are each P2405 inside a nothrow body;
  • a call to a function that declares nothing does not break it: such a function may throw anything, and no finding is built on that;
  • a call to a nothrow function is not a throw point, so a catch around such calls alone is dead (P2403).

nothrow is not a guarantee at run time. A TypeError from a callee that declares nothing, or an Error PHP raises on its own, can still escape.

nothrow and throws together are a syntax error. nothrow beside a docblock @throws tag that names an exception, or a throws clause beside a @throws void tag, is P2320.

Inheritance

A method that declares nothing takes the declaration of the method it overrides or implements: its throws clause, its @throws tags or its nothrow. So an implementation of a nothrow interface method is held to it:

you write
namespace App;

interface Repository
{
    find(int $id): ?object nothrow;
}

final class SqlRepository implements Repository
{
    find(int $id): ?object {
        if ($id < 0) {
            throw new \InvalidArgumentException('negative id');
        }

        return null;
    }
}
$ phn checkexit 1
src/Example.phn:12:13: error P2405: App\SqlRepository::find() inherits nothrow from App\Repository::find() but throws InvalidArgumentException here
   12 |             throw new \InvalidArgumentException('negative id');
      |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1 files checked: 1 errors, 0 warnings

An override that writes its own clause is held to that clause only, not to the parent's: the 0.7.2 checker, like PHPStan, does not compare an override's throws with its parent's.

What the checker reports

CodeSeverityWhen
P2319errorthrows names a class that is not a Throwable
P2320errornothrow or @throws void beside a thrown type
P2403warningA catch that nothing in its try block can reach
P2404warningA throws member the body never throws
P2405errorA nothrow (or @throws void) body that throws, inherited or written
you write
namespace App;

final class Money {}

final class Cache
{
    private load(): int throws \RuntimeException => 1;

    get(): int {
        try {
            return $this->load();
        } catch (\LogicException $e) {
            return 0;
        }
    }

    total(): int throws Money => $this->get();
}
$ phn checkexit 1
src/Example.phn:7:13: warning P2404: App\Cache::load() declares it throws RuntimeException, which its body never throws
    7 |     private load(): int throws \RuntimeException => 1;
      |             ^^^^
src/Example.phn:12:18: warning P2403: LogicException is never thrown in the try block
   12 |         } catch (\LogicException $e) {
      |                  ^^^^^^^^^^^^^^^
src/Example.phn:17:25: error P2319: App\Money is not a Throwable, so throws cannot name it
   17 |     total(): int throws Money => $this->get();
      |                         ^^^^^
1 files checked: 1 errors, 2 warnings

In the compiled PHP

throws A|B becomes a @throws A|B line in the declaration's docblock, and nothrow becomes @throws void. The compiler adds the docblock when there is none, and adds the line to one that exists. Nothing else changes: PHP does not read the tag, and PHPStan, PhpStorm and the checker do.

Migrating

phn migrate lifts the @throws tags that have no description into a throws clause, several tags into one union, and a @throws void that is the only @throws tag into nothrow. A tag with a description stays in the docblock. This PHP:

final class Account
{
    private int $balance = 0;

    /**
     * @throws void
     */
    public function balance(): int
    {
        return $this->balance;
    }

    /**
     * @throws \DomainException
     * @throws \OverflowException
     */
    public function close(): void
    {
        $this->withdraw($this->balance);
    }
}

becomes:

final class Account
{
    private int $balance = 0;

    balance(): int nothrow => $this->balance;

    close(): void throws \DomainException|\OverflowException => $this->withdraw($this->balance);
}

See also