The PHP exceptions' cheat sheet

Published on 2021-10-02 • Modified on 2021-10-02

This post is different from what I use to do. It will be a reference, a "cheat sheet" mentioning all available exceptions with PHP. Let's go! 😎

Prerequisite

I will assume you have at least a basic knowledge of PHP.

Configuration

The following post is based on PHP 7.4, but there are few differences with PHP 8.

Introduction

Sometimes when I code, I am not always sure of the "best" exception to use. Also, as I don't have a fantastic memory, I always have to search in the documentation or the web. That's why I wanted to have a clean reference that regroups everything to find what I need quickly.

Goal

The goal is to present errors and exceptions in two different ways. First, I'll display them as hierarchical trees. Then, I'll show them as tables in a cleaner and complete way.

The trees

First, let's see the simple tree which gives a good overview of all errors, exceptions and the associated sub-classes:



Click here to see the code to get this tree dynamically. You must call printTree().
                                    'fqcn' => \UnderflowException::class,
                                    'doc' => 'https://www.php.net/manual/en/class.underflowexception',
                                    'stackoverflow' => 'https://stackoverflow.com/q/69301995/633864',
                                    'parent' => \RuntimeException::class,
                                    'links' => ['https://airbrake.io/blog/php-exception-handling/underflowexception'],
                                ],
                                \UnexpectedValueException::class => [
                                    'fqcn' => \UnexpectedValueException::class,
                                    'doc' => 'https://www.php.net/manual/en/class.unexpectedvalueexception',
                                    'stackoverflow' => 'https://stackoverflow.com/q/34133049/633864',
                                    'parent' => \RuntimeException::class,
                                    'links' => ['https://airbrake.io/blog/php-exception-handling/unexpectedvalueexception-2'],
                                ],
                            ],
                        ],
                        \SoapFault::class => [
                            'fqcn' => \SoapFault::class,
                            'doc' => 'https://www.php.net/manual/en/soapfault.construct',
                            'stackoverflow' => 'https://stackoverflow.com/q/19612481/633864',
                            'parent' => \Exception::class,
                            'links' => ['https://hotexamples.com/examples/-/SoapFault/-/php-soapfault-class-examples.html'],
                        ],
                        \SodiumException::class => [
                            'fqcn' => \SodiumException::class,
                            'doc' => 'https://www.php.net/manual/en/class.sodiumexception',
                            'stackoverflow' => 'https://stackoverflow.com/q/54587528/633864',
                            'parent' => \Exception::class,
                        ],
                    ],
                ],
            ],
        ],
    ];

    /**
     * @return array<string>
     */
    private function listThrowableClasses(): array
    {
        $result = [];
        if (interface_exists('Throwable')) {
            foreach (get_declared_classes() as $cn) {
                $implements = class_implements($cn);
                if ($implements === false) {
                    continue;
                }

                if (isset($implements['Throwable'])) {
                    $result[] = $cn;
                }
            }
        } else {
            foreach (get_declared_classes() as $cn) {
                if ($cn === 'Exception' || is_subclass_of($cn, 'Exception')) {
                    $result[] = $cn;
                }
            }
        }

        return $result;
    }

    /**
     * @param array<string> $classes
     *
     * @return array<mixed>
     */
    private function groupByParents(array $classes): array
    {
        $result = [];
        foreach ($classes as $cn) {
            $parent = (string) get_parent_class($cn);
            if (isset($result[$parent])) {
                $result[$parent][] = $cn;
            } else {
                $result[$parent] = [$cn];
            }
        }

        return $result;
    }

    /**
     * @return array<mixed>
     */
    public function getExceptionsHierarchy(): array
    {
        $throwables = $this->listThrowableClasses();

        return $this->groupByParents($throwables);
    }

    public function printTree(): void
    {
        $tree = $this->getExceptionsHierarchy();

        // echo '<pre>';
        $this->printLeaves($tree, '', 0);
        // die();
    }

    /**
     * @param array<mixed> $tree
     */
    public function printLeaves(array &$tree, string $parent, int $level): void
    {
        if (isset($tree[$parent])) {
            /** @var array<string> $leaves */
            $leaves = $tree[$parent];
            unset($tree[$parent]);
            natcasesort($leaves);
            $leaves = array_values($leaves);
            foreach ($leaves as $leaf) {
                echo str_repeat('   ', $level), $leaf, "\n";
                $this->printLeaves($tree, $leaf, $level + 1);
            }
        }
    }
}

You can find the original sources here:

Now, let's see the entire tree. Click on the nodes to expand and click on the "children" nodes to see all objects extending the parent classes. The documentation, StackOverflow and other links are clickable. Click below on "{1 item}" to start:



The data

Now, let's display all these information in a more convenient way. As of PHP 7, errors and exceptions extend the Throwable class. Errors are for PHP internal errors and exceptions are for all other cases.

Throwable

FQCN Description Parent Children Links SO Doc
\Throwable Throwable is the base interface for any object that can be thrown via a throw statement, including Error and Exception. - Error, Exception

Errors

FQCN Description Parent Children Links SO Doc
\Error Error is the base class for all internal PHP errors. Throwable ArithmeticError, AssertionError, CompileError, TypeError, ValueError, UnhandledMatchError, FiberError -
FQCN Description Parent Children Links SO Doc
\ArithmeticError ArithmeticError is thrown when an error occurs while performing mathematical operations. These errors include attempting to perform a bitshift by a negative amount, and any call to intdiv() that would result in a value outside the possible bounds of an int. Error DivisionByZeroError
FQCN Description Parent Children Links SO Doc
\DivisionByZeroError DivisionByZeroError is thrown when an attempt is made to divide a number by zero. ArithmeticError -
FQCN Description Parent Children Links SO Doc
\AssertionError AssertionError is thrown when an assertion made via assert() fails. Error -
FQCN Description Parent Children Links SO Doc
\CompileError CompileError is thrown for some compilation errors, which formerly issued a fatal error. Error ParseError
FQCN Description Parent Children Links SO Doc
\ParseError ParseError is thrown when an error occurs while parsing PHP code, such as when eval() is called. Note: ParseError extends CompileError as of PHP 7.3.0. Formerly, it extended Error. CompileError -
FQCN Description Parent Children Links SO Doc
\TypeError A TypeError may be thrown when:
  • The value being set for a class property does not match the property's corresponding declared type.
  • The argument type being passed to a function does not match its corresponding declared parameter type.
  • A value being returned from a function does not match the declared function return type.
Error ArgumentCountError
FQCN Description Parent Children Links SO Doc
\ArgumentCountError ArgumentCountError is thrown when too few arguments are passed to a user-defined function or method. TypeError - -
FQCN Description Parent Children Links SO Doc
\ValueError A ValueError is thrown when the type of an argument is correct but the value of it is incorrect. For example, passing a negative integer when the function expects a positive one, or passing an empty string/array when the function expects it to not be empty. Error
FQCN Description Parent Children Links SO Doc
\UnhandledMatchError An UnhandledMatchError is thrown when the subject passed to a match expression is not handled by any arm of the match expression. Error
FQCN Description Parent Children Links SO Doc
\FiberError FiberError is thrown when an invalid operation is performed on a Fiber. Error

Exceptions

FQCN Description Parent Children Links SO Doc
\Exception Exception is the base class for all user exceptions. Throwable ClosedGeneratorException, DOMException, ErrorException, IntlException, JsonException, LogicException, PharException, ReflectionException, RuntimeException, SoapFault, SodiumException
FQCN Description Parent Children Links SO Doc
\ClosedGeneratorException A ClosedGeneratorException occurs when attempting to perform a traversal on a generator that has already been closed or terminated. Exception - -
FQCN Description Parent Children Links SO Doc
\DOMException DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons. Exception -
FQCN Description Parent Children Links SO Doc
\ErrorException ErrorException is mostly used to convert php error (raised by error_reporting) to Exception. Exception -
FQCN Description Parent Children Links SO Doc
\IntlException This class is used for generating exceptions when errors occur inside intl functions. Such exceptions are only generated when intl.use_exceptions is enabled. Exception -
FQCN Description Parent Children Links SO Doc
\JsonException Exception thrown if JSON_THROW_ON_ERROR option is set for json_encode() or json_decode(). code contains the error type, for possible values see json_last_error(). Exception -
FQCN Description Parent Children Links SO Doc
\LogicException Exception that represents error in the program logic. This kind of exception should lead directly to a fix in your code. Exception BadFunctionCallException, DomainException, InvalidArgumentException, LengthException, OutOfRangeException
FQCN Description Parent Children Links SO Doc
\BadFunctionCallException Exception thrown if a callback refers to an undefined function or if some arguments are missing. LogicException BadMethodCallException
FQCN Description Parent Children Links SO Doc
\BadMethodCallException Exception thrown if a callback refers to an undefined method or if some arguments are missing. BadFunctionCallException -
FQCN Description Parent Children Links SO Doc
\DomainException Exception thrown if a value does not adhere to a defined valid data domain. LogicException -
FQCN Description Parent Children Links SO Doc
\InvalidArgumentException Exception thrown if an argument is not of the expected type. LogicException -
FQCN Description Parent Children Links SO Doc
\LengthException Exception thrown if a length is invalid. LogicException -
FQCN Description Parent Children Links SO Doc
\OutOfRangeException Exception thrown when an illegal index was requested. This represents errors that should be detected at compile time. LogicException -
FQCN Description Parent Children Links SO Doc
\PharException The PharException class provides a phar-specific exception class for try/catch blocks. Exception -
FQCN Description Parent Children Links SO Doc
\ReflectionException The ReflectionException class. Exception -
FQCN Description Parent Children Links SO Doc
\RuntimeException Exception thrown if an error which can only be found on runtime occurs. Exception OutOfBoundsException, OverflowException, PDOException, RangeException, UnderflowException, UnexpectedValueException
FQCN Description Parent Children Links SO Doc
\OutOfBoundsException Exception thrown if a value is not a valid key. This represents errors that cannot be detected at compile time. RuntimeException -
FQCN Description Parent Children Links SO Doc
\OverflowException Exception thrown when adding an element to a full container. RuntimeException -
FQCN Description Parent Children Links SO Doc
\PDOException Represents an error raised by PDO. You should not throw a PDOException from your own code. See Exceptions for more information about Exceptions in PHP. RuntimeException -
FQCN Description Parent Children Links SO Doc
\RangeException Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of DomainException. RuntimeException -
FQCN Description Parent Children Links SO Doc
\UnderflowException Exception thrown when performing an invalid operation on an empty container, such as removing an element. RuntimeException -
FQCN Description Parent Children Links SO Doc
\UnexpectedValueException Exception thrown if a value does not match with a set of values. Typically this happens when a function calls another function and expects the return value to be of a certain type or value not including arithmetic or buffer related errors. RuntimeException -
FQCN Description Parent Children Links SO Doc
\SoapFault This class is used to send SOAP fault responses from the PHP handler. faultcode, faultstring, faultactor and detail are standard elements of a SOAP Fault. Exception -
FQCN Description Parent Children Links SO Doc
\SodiumException Exceptions thrown by the sodium functions. Exception - -

As this is a reference, I'll update this page as soon as I find interesting examples or more helpful explanations to add.

Conclusion

Exceptions aren't so easy to use. It's sometimes hard to choose the right one. But as you get used to them, it becomes less and less challenging to spot the good one to use depending on your use case. I hope this cheat sheet will help you make the right choice and to have a better global knowledge of all PHP exceptions and errors.

That's it! I hope you like it. Check out the links below to have additional information related to the post. As always, feedback, likes and retweets are welcome. (see the box below) See you! COil. 😊

  Read the doc  More on the web  More on Stackoverflow

  Work with me!


Call to action

Did you like this post? You can help me back in several ways: (use the Tweet on the right to comment or to contact me )

Thank you for reading! And see you soon on Strangebuzz! 😉

COil