Introduction
Things go wrong in programs: a user gives a bad number, a value is missing, a division by zero happens. If your code ignores problems, it prints wrong results or stops with a long error message. Exceptions are PHP's way to report a problem and to let you decide what to do. When a function cannot continue, it throws an exception. The caller can catch it, show a friendly message and keep the program running. This lesson shows how to use them well.
How it works
You throw an exception with the keyword throw and an object:
throw new InvalidArgumentException("Cannot divide by zero");
The throw stops the current function at once, and PHP looks upwards through the callers for a matching catch. The place where you expect a problem is wrapped in a try block:
try {
echo divide(1, 0);
} catch (InvalidArgumentException $e) {
echo "Error: ", $e->getMessage();
} finally {
echo "always runs";
}
If an exception is thrown in the try block, the rest of the block is skipped and the matching catch runs. The finally block runs in every case, even if the code returns early, and it is the right place to clean up. If nothing catches the exception, the program ends with a fatal error.
Exceptions are objects of classes that form a family. The base is Throwable, and under it are Exception and Error. Common ones you can throw yourself are InvalidArgumentException for a bad argument, LengthException, RuntimeException for problems found while running, and LogicException for mistakes in the code. PHP itself throws DivisionByZeroError for intdiv(5, 0) and 7 % 0, and TypeError when a value has the wrong type. The object has useful methods: getMessage(), getCode() and getPrevious().
You can write your own exception by extending Exception. It can carry extra data, for example how much money is missing, and your catch code can use it. Catch the most specific class first. You can catch two kinds in one block with a bar: catch (A | B $e). If you catch Exception you catch almost everything, so do this only at the top of the program.
To keep the original reason, pass it as the third argument when you throw a new exception: new LogicException("outer problem", 0, $e). Later getPrevious() returns the first one. This is called chaining.
Use exceptions for unexpected problems, not for normal decisions. Checking if ($n > 0) is simpler than catching an error for a value you can predict.
Example
<?php
class InsufficientFunds extends Exception
{
public function __construct(private int $needed)
{
parent::__construct("Need $needed more");
}
public function getNeeded(): int
{
return $this->needed;
}
}
function divide(int $a, int $b): float
{
if ($b === 0) {
throw new InvalidArgumentException("Cannot divide by zero");
}
return $a / $b;
}
function withdraw(int $balance, int $amount): int
{
if ($amount > $balance) {
throw new InsufficientFunds($amount - $balance);
}
return $balance - $amount;
}
try {
echo divide(10, 4), "\n";
echo divide(1, 0), "\n";
echo "not reached\n";
} catch (InvalidArgumentException $e) {
echo "Error: ", $e->getMessage(), "\n";
} finally {
echo "finally runs\n";
}
try {
echo withdraw(50, 20), "\n";
echo withdraw(50, 80), "\n";
} catch (InsufficientFunds $e) {
echo $e->getMessage(), " (", $e->getNeeded(), ")\n";
}
try {
echo 7 % 0;
} catch (DivisionByZeroError $e) {
echo "Caught: ", $e->getMessage(), "\n";
}
try {
echo intdiv(5, 0);
} catch (DivisionByZeroError | TypeError $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
function risky(): void
{
try {
throw new RuntimeException("inner problem");
} catch (RuntimeException $e) {
throw new LogicException("outer problem", 0, $e);
}
}
try {
risky();
} catch (LogicException $e) {
echo $e->getMessage(), " caused by ", $e->getPrevious()->getMessage(), "\n";
}Line by line
InsufficientFundsextendsExceptionand stores how much money is missing.dividethrows anInvalidArgumentExceptionwhen the divisor is zero.- The first
tryprints 2.5, then the second call throws. The code after it is skipped,catchprints the message andfinallyalways runs. withdrawsucceeds with 30, then fails and throws the custom exception with its data.- PHP throws
DivisionByZeroErrorfor7 % 0, and the catch prints its message. - One
catchhandles two classes, andget_classshows which one happened. riskycatches one exception and throws another with the first one inside it.getPrevious()shows the cause.
Expected result
2.5
Error: Cannot divide by zero
finally runs
30
Need 30 more (30)
Caught: Modulo by zero
DivisionByZeroError: Division by zero
outer problem caused by inner problem
In the real world
Real applications meet bad input every day: forms with wrong data, services that are down and files that are missing. Good exception handling shows a clear message to the user, writes the details to a log and keeps the rest of the application working. Frameworks have one central place that catches every exception and turns it into an error page.
Common mistakes
- Catching
Exceptioneverywhere and hiding real bugs. - Writing an empty catch block, so nobody sees the problem.
- Using exceptions for normal flow that an
ifcan handle. - Catching a general class before a specific one, so the specific block never runs.
Best practices
- Throw the most specific class you can, and write your own for your own rules.
- Give messages that tell what was wrong and what was expected.
- Use
finallyfor clean-up work. - Validate input early, close to where it enters the program.
Summary
throw reports a problem, try guards code, catch handles a class of exceptions and finally always runs. Exceptions are objects with a message, a code and an optional previous exception. PHP throws errors such as DivisionByZeroError and TypeError itself, and you can extend Exception for your own cases.
Quick check
Key takeaways
- throw reports a problem and catch handles it.
- finally always runs.
- Write your own exception classes for your own rules.
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.