Skip to main content

How to Catch an Exception in PHP

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

When code hits a problem it can't handle, it throws an exception, and the script stops unless something catches it. Wrapping the call in try and naming the exception's class in catch lets you handle the failure you expected and carry on.

Syntax​

Syntax
try {
// code that may throw
} catch (<ExceptionClass> $<e>) {
// handle it, for example with $<e>->getMessage()
}
PartWhat it does
try { ... }Runs the code that may throw.
catch (<ExceptionClass> $<e>)Runs only for that class or a class that extends it.
$<e>->getMessage()The message the exception was created with.

The PHP manual on errors and exceptions: "It is possible to handle a Throwable error within PHP by surrounding the code that may throw an error in a try block." And: "When a Throwable error is thrown, it will unwind the call stack until it is caught by a catch block or the global scope is reached."

The Example​

The example converts text to a number. For forty-two the function throws an InvalidArgumentException, which the catch block reports.

Prerequisites​

  • PHP for the command line. This guide uses PHP 8.6.0.

Step 1: Write the Code​

Create a file named main.php:

main.php, which defines toNumber(string $text): int that throws an InvalidArgumentException for non-numeric text, and calls it for 42 and forty-two inside try, echoing Caught: with the message in the catch block.

main.php
<?php

function toNumber(string $text): int
{
if (!is_numeric($text)) {
throw new InvalidArgumentException("Not a number: $text");
}
return (int) $text;
}

try {
echo toNumber('42'), "\n";
echo toNumber('forty-two'), "\n";
} catch (InvalidArgumentException $e) {
echo "Caught: ", $e->getMessage(), "\n";
}
  • throw new InvalidArgumentException(...) creates the exception and stops the function.
  • The second echo inside try never runs: the exception jumps straight to catch.

Step 2: Run It​

Terminal
php main.php
Output
42
Caught: Not a number: forty-two

A zsh terminal where php main.php prints 42 and Caught: Not a number: forty-two.

The command is the same in zsh, bash and PowerShell.

Catching a Parent Class​

Exceptions form a family tree: InvalidArgumentException extends LogicException, which extends Exception. A catch (Exception $e) caught the InvalidArgumentException too. Catch the specific class when only that failure is expected, and a parent class when a whole family should be handled the same way. Throwable sits above both Exception and PHP's own Error classes.

Common Mistakes​

MistakeWhat happensDo this instead
No try around a call that throwsFatal error: Uncaught InvalidArgumentException: Not a number: forty-two and exit code 255Catch it where you can handle it
Catching Exception and expecting a TypeErrorTypeError is an Error, not an Exception, so it isn't caughtCatch TypeError, or Throwable
An empty catch blockThe failure disappears silentlyAt least log $e->getMessage()

Troubleshooting​

SymptomLikely causeFix
Fatal error: Uncaught …Nothing caught the exceptionAdd a try/catch for that class
The catch block never runsThe thrown class isn't the one named, or a child of itCatch the class named in the error message

FAQ​

Can one catch handle several classes?​

Yes, with |: catch (InvalidArgumentException | TypeError $e).

Is there a finally block?​

Yes. finally { ... } after the catch runs whether or not an exception was thrown.

Conclusion​

Wrap risky calls in try, handle the expected class in catch, and read the reason with getMessage(). A parent class catches its children, so name the class that fits the failures you can handle.

Additional Resources​