PHP Reference ยท Exceptions and Errors
PHP RuntimeException class
Reference for PHP RuntimeException and its subclasses (OutOfBoundsException, OverflowException, UnexpectedValueException...): when to use them, with examples.
RuntimeException is the SPL exception for errors that can only be detected while the program runs and that careful argument checking could not have prevented: a file that is missing, a service that fails, a value that comes out of storage in the wrong shape. It is the counterpart of LogicException, which marks bugs in the calling code.
It has several subclasses, which let callers catch a more precise condition while the parent still catches them all.
if (!is_readable($path)) { throw new RuntimeException("Cannot read $path"); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
class RuntimeException extends Exception {} new RuntimeException(string $message = "", int $code = 0, ?Throwable $previous = null);
| Subclass | Typical use |
|---|---|
OutOfBoundsException |
A key or index that does not exist in a collection. |
OverflowException |
Adding to a container that is full. |
UnderflowException |
Removing from a container that is empty. |
RangeException |
A computed value lies outside the allowed range. |
UnexpectedValueException |
A value does not match the expected type or shape, for example a callback returns the wrong kind of value. |
Usage notes
- Runtime versus logic. If the caller could have avoided it by checking arguments, use
InvalidArgumentException. If the environment or the data caused it, useRuntimeException. - Wrap lower-level failures. Pass the original as
$previous, as the second example does, to keep the cause while exposing an exception that belongs to your layer. OutOfRangeExceptionis a different class. It extendsLogicExceptionand is for illegal indexes in code;OutOfBoundsExceptionis its runtime counterpart.- Catch the parent for groups.
catch (RuntimeException $e)handles every subclass above. - Prefer your own subclass for failures a caller wants to handle separately (see Custom exceptions).
- Other classes.
PDOExceptionextendsRuntimeException, butJsonExceptionandErrorExceptionextendExceptiondirectly.