Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PHP
PHP
0/12 completed
Beginner
Hello PHPVariables and arraysControl flowFunctions
Intermediate
Strings, dates and JSONForms, requests and sessionsDatabases with PDO
Advanced
Object-oriented PHPErrors, exceptions and typesSecurity essentials
Pro
Composer, autoloading and testingLaravel basics
Tracks / PHP / Advanced

Errors, exceptions and types

PHP 8 turned many old warnings into proper exceptions, and added a strong type system. Used together they make bugs loud and early: a wrong type or a failed operation stops right where it happened, with a clear message, instead of producing a wrong page three steps later. This lesson covers both.

Exceptions: try, catch, finally

PHP · editable
  • throw new SomeException("message") raises an exception.
  • catch (A | B $e) handles one or several types; the first matching catch wins.
  • finally always runs, whether or not an exception happened, which makes it the place to clean up.

The hierarchy: Exception and Error

Everything you can throw implements Throwable, which has two families:

PHP · editable
  • Error means a programming bug: calling an undefined function, a type error, division by zero. You generally fix these rather than catch them.
  • Exception means something that can legitimately go wrong at run time: invalid input, a missing file, a failed database query. These are what you catch.
  • catch (Throwable $t) catches both, which is right only at the very top of an app (to log and show an error page).

Your own exception classes

PHP · editable

A common base class (ShopException) lets callers catch every error from your code at once, while specific classes carry extra data.

Wrapping exceptions

When you catch a low-level exception and throw a more meaningful one, pass the original as previous, so nothing is lost:

PHP · editable

Uncaught exceptions

If nothing catches an exception, PHP prints a fatal error with the stack trace and stops:

PHP · editable

Note ?? throw …: since PHP 8, throw is an expression, so it can be used after ?? and in arrow functions.

In production, set display_errors=Off (so visitors never see stack traces), log_errors=On, and register a top-level handler that logs the error and shows a friendly page. Frameworks like Laravel do all of this for you.

Types in depth

Declaring types everywhere, with strict_types, turns many bugs into immediate, precise errors:

PHP · editable
Type feature Example
Scalar types int, float, string, bool
Nullable ?string (string or null)
Union int|float
Intersection Countable&Traversable (must be both)
mixed, void, never, static, self Special types
Typed properties private array $lines = [];
readonly Set once, then fixed

Static analysis

Types also let tools check your code without running it. PHPStan and Psalm read your types (and docblocks like @var list<…>) and find bugs such as calling a method on something that might be null. Install with Composer and run vendor/bin/phpstan analyse src --level=6. Most professional PHP projects run one in CI.

Warnings and notices

Some problems still produce warnings instead of exceptions, and the script continues:

PHP · editable

Treat warnings as bugs. In development, use an error handler (or your framework's) that turns them into exceptions, so they can't be ignored:

PHP · editable

Practice

  1. Write divide(float $a, float $b): float that throws InvalidArgumentException for division by zero, and call it inside try/catch.
  2. Create ValidationException that carries an array of field errors, and print them all when it's caught.
  3. Add declare(strict_types=1) to a script of yours, and fix every TypeError it reveals.
  4. Use ?? throw to require a $_GET-style array key.
✎ Check your understanding

1.When does a finally block run?

2.What's the difference between Error and Exception in PHP 8?

3.Why pass previous: $e when throwing a new exception?

4.What does ?? throw new Exception(...) do?

← Object-oriented PHP