In this chapter
We'll learn the errors PHP itself throws — TypeError, ArgumentCountError, ValueError, DivisionByZeroError, UnhandledMatchError, JsonException and ParseError — which failures are still classic warnings that return false, the fatal errors no code can catch, and the error levels like E_WARNING and E_DEPRECATED that PHP uses to label every message.
The Problem in Real Life
Testing the admin screen, Mia collects a strange set of failures in one afternoon. The price field arrives as the text "27.50" and PHP throws a TypeError. A broken settings.json makes json_decode() return null — with no error at all. A report that loads every booking since 2020 dies with "Allowed memory size of 134217728 bytes exhausted", and her catch (Throwable $e) around it never runs.
Meanwhile file_get_contents() on a missing file prints a warning, returns false, and the code carries on, treating false as an empty list of holidays.
Some of these throw, some just warn, one says nothing and one can't be caught at all. How do I know which is which?
Mia
Guessing How PHP Fails vs. Knowing Each Kind
Errors PHP throws
Wrong types, wrong values, impossible maths and unmatched match arms throw Error objects.
Warnings that return false
Many file and network functions still only warn — your code must check the result.
Truly fatal
Memory and time limits and broken syntax end the script before any catch can help.
PHP's Built-In Errors
The errors PHP raises by itself: your own exceptions are only half the picture. PHP's engine and built-in functions report problems too, in different ways. This chapter covers:
- TypeError and ArgumentCountError: the wrong type or number of arguments.
- ValueError and DivisionByZeroError: right type, impossible value.
- Other built-in errors: UnhandledMatchError, JsonException and more.
- ParseError and real fatal errors: what no catch can stop.
- Warnings, notices, deprecations: the error levels.
TypeError: thrown when a value has the wrong type for a parameter, a return value or a typed property (Acts 04, 09 and 12). With declare(strict_types=1);, passing the string "12" to an int parameter throws "price(): Argument #1 ($p) must be of type int, string given"; without strict types, PHP converts "12" but still throws for a value it can't convert, like an array. Built-in functions throw it too: strlen([]) gives "strlen(): Argument #1 ($string) must be of type string, array given". A TypeError is a bug at the boundary where data enters the code — convert and validate form input first (Act 17), then pass real ints inside.
<?phpdeclare(strict_types=1);function chargePence(int $pence): string{return "Charged {$pence}p";}try {echo chargePence("2750"), "\n"; // a string from a form} catch (TypeError $e) {echo get_class($e), ": ", $e->getMessage(), "\n";}echo chargePence((int) "2750"), "\n"; // convert at the boundary// TypeError: chargePence(): Argument #1 ($pence) must be of type int, string given, called in main.php on line 11// Charged 2750p
ArgumentCountError: a child of TypeError, thrown when a function gets too few arguments: "Too few arguments to function f(), 1 passed in main.php on line 9 and exactly 2 expected". Your own functions accept extra arguments silently, but built-in functions throw for too many too.
ValueError: the type is right but the value is impossible. str_repeat("x", -1) throws "str_repeat(): Argument #2 ($times) must be greater than or equal to 0", and array_combine() with arrays of different lengths throws because they "must have the same number of elements". Before PHP 8, both returned false with a warning, and the false travelled on into the rest of the code.
ArithmeticError and DivisionByZeroError: since PHP 8, dividing by zero throws DivisionByZeroError — "Division by zero" for / and intdiv(), "Modulo by zero" for %. Its parent, ArithmeticError, covers other impossible maths, like an integer division whose result doesn't fit in an int. Check divisors that come from data: an average over zero bookings is a classic.
UnhandledMatchError, JsonException and friends: a match with no matching arm and no default throws UnhandledMatchError ("Unhandled match case 'closed'") — Act 06's safety net. json_decode() is a trap: on broken JSON it returns null silently, and you have to ask json_last_error_msg(). With the flag JSON_THROW_ON_ERROR it throws JsonException ("Syntax error") instead — always pass it (Act 19). Since PHP 8.3, new DateTimeImmutable("not a date") throws DateMalformedStringException. The table below collects all of them.
| Class | Parent | Example | Message |
|---|---|---|---|
| TypeError | Error | strlen([]) | strlen(): Argument #1 ($string) must be of type string, array given |
| ArgumentCountError | TypeError | f(1) for f(int $a, int $b) | Too few arguments to function f(), 1 passed … and exactly 2 expected |
| ValueError | Error | str_repeat("x", -1) | … Argument #2 ($times) must be greater than or equal to 0 |
| DivisionByZeroError | ArithmeticError | 1 % 0 | Modulo by zero |
| UnhandledMatchError | Error | match ("closed") { "open" => … } | Unhandled match case 'closed' |
| ParseError | CompileError | eval('echo ;') | syntax error, unexpected token ";" |
| JsonException | Exception | json_decode('{bad', flags: JSON_THROW_ON_ERROR) | Syntax error |
| DateMalformedStringException | Exception (8.3) | new DateTimeImmutable("not a date") | Failed to parse time string (not a date) … |
| ErrorException | Exception | Thrown by your error handler (chapter 5) | The warning's message |
<?phpfunction f(int $a, int $b) { return $a + $b; }$tests = [fn() => strlen([]),fn() => f(1),fn() => str_repeat("x", -1),fn() => 1 % 0,fn() => match ("closed") { "open" => "welcome" },fn() => json_decode('{bad', flags: JSON_THROW_ON_ERROR),fn() => new DateTimeImmutable("not a date"),];foreach ($tests as $test) {try {$test();} catch (Throwable $e) {echo str_pad(get_class($e), 30), $e->getMessage(), "\n";}}
<?php$settings = json_decode('{"holidayPercent": 10'); // a missing }var_dump($settings); // NULL — and no error messageecho json_last_error_msg(), "\n"; // Syntax errortry {json_decode('{"holidayPercent": 10', flags: JSON_THROW_ON_ERROR);} catch (JsonException $e) {echo "JsonException: ", $e->getMessage(), "\n";}// NULL// Syntax error// JsonException: Syntax error
ParseError and real fatal errors: a syntax error in a file means PHP can't compile it, so none of that file runs — not even its try. A ParseError can only be caught by code in another file that includes it (or by eval()), which is why a typo can still give a white page. A few problems aren't Throwables at all and can't be caught: running out of memory ("Allowed memory size of … bytes exhausted"), exceeding max_execution_time, declaring a class twice. PHP stops the script on the spot. Only a shutdown function can still notice them (chapter 5). PHP 8.5 adds a stack trace to fatal errors (the fatal_error_backtraces setting, on by default), so the log now shows how the script got there.
Three ways PHP reports a problem
A problem in PHP
Throws an Error or Exception
TypeError, ValueError, JsonException…
Reports a warning / notice / deprecation
file_get_contents() → false
Fatal error, not a Throwable
memory, time limit, syntax
catch can handle it
uncaught → fatal
script carries on
check the result, or convert it (ch. 5)
script stops at once
only a shutdown function notices
<?phpini_set('memory_limit', '4M');try {$bookings = [];while (true) {$bookings[] = str_repeat('x', 1000); // keeps growing}} catch (Throwable $e) {echo "never printed\n";}// Fatal error: Allowed memory size of 4194304 bytes exhausted (tried to allocate 20480 bytes) in report.php on line 8
Warnings, notices and deprecations: not everything throws. Functions that work with files, the network or the system often only raise a warning and return false: file_get_contents() on a missing file warns "Failed to open stream: No such file or directory" and returns false. Reading an undefined array key or variable is a warning too. A deprecation says "this still works, but will stop working in a future version". Each message has a level — a constant like E_WARNING — and chapter 5 decides which levels are reported. For warnings, the rule is: check the return value (if ($json === false)), or turn warnings into exceptions with an error handler (chapter 5). The second table lists the levels.
| Constant | Value | Meaning | Script continues? |
|---|---|---|---|
| E_ERROR | 1 | Fatal run-time error (memory, time limit) | No |
| E_WARNING | 2 | Something failed, e.g. a file couldn't be opened | Yes |
| E_PARSE | 4 | Syntax error while compiling | No |
| E_NOTICE | 8 | Minor hint (rare since PHP 8) | Yes |
| E_DEPRECATED | 8192 | Works now, will stop working later | Yes |
| E_USER_WARNING / E_USER_DEPRECATED | 512 / 16384 | Raised by your code with trigger_error() | Yes |
| E_ALL | 30719 (PHP 8.5) | Every level | — |
<?php$json = file_get_contents('/srv/bookbay/holidays.json'); // missing filevar_dump($json);if ($json === false) {echo "Could not read the holiday list\n";}// Warning: file_get_contents(/srv/bookbay/holidays.json): Failed to open stream: No such file or directory in main.php on line 3// bool(false)// Could not read the holiday list
Key Takeaway
PHP throws Error subclasses for bugs: TypeError (wrong type; ArgumentCountError for missing arguments), ValueError (impossible value), DivisionByZeroError for / and % by zero, UnhandledMatchError, and DateMalformedStringException since 8.3; json_decode() fails silently unless you pass JSON_THROW_ON_ERROR. A ParseError stops the whole file, so only code in another file can catch it, and memory or time limits end the script with an uncatchable fatal error (8.5 adds a backtrace). Many file and network functions only warn and return false — check results. Every message has a level such as E_WARNING or E_DEPRECATED.
Why This Matters
Knowing how each built-in function fails is what separates code that works on the happy path from code that survives real data: a missing file, a broken JSON payload, an empty list to average.
PHP 8 made the language much stricter — more throws, fewer silent falses. Older tutorials and code still check === false everywhere, and some of those checks can no longer ever be true, while others (files, JSON without the flag) are still essential.
Mia now passes JSON_THROW_ON_ERROR, checks file_get_contents() for false, and the report loads bookings in pages. But checking every file call by hand is easy to forget, and the memory-limit failure still leaves a white page with nothing friendly on it. Marcus wants three things set up once for the whole project: which messages PHP reports, warnings turned into exceptions, and a last-resort handler for anything uncaught. That's the next chapter: error handlers and error reporting.
