Skip to main content

How to Throw an Exception in PHP

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

In PHP, throw new InvalidArgumentException('...') stops the current function and hands an exception to whoever called it. A try and catch around the call can handle it; if nothing does, PHP ends the script with a fatal error.

Syntax​

Syntax
throw new <ExceptionClass>(<message>);
PartWhat it does
throwStops the code here and passes the exception up to the code that called it.
new <ExceptionClass>(...)Creates the exception, such as InvalidArgumentException for a bad argument.
<message>Text that explains the problem. getMessage() returns it.

The PHP manual: "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." and "An uncaught Throwable error is passed to the exception handler set with set_exception_handler(), if one is set; otherwise, the program is terminated with a fatal error."

The Example​

The example has a function that throws InvalidArgumentException for a negative age. It calls the function inside try with a good age and then a bad one, and once more outside try, where nothing catches the exception.

Prerequisites​

  • PHP 8. This guide uses PHP 8.6.0.

Step 1: Write the Code​

Create a file named main.php:

main.php, whose checkAge function throws an InvalidArgumentException for a negative age, called with 30 and -1 inside try with a catch that echoes the message, and with -5 outside it.

main.php
<?php

declare(strict_types=1);

function checkAge(int $age): void
{
if ($age < 0) {
throw new InvalidArgumentException("Age can't be negative: {$age}");
}
echo "Age {$age} is fine\n";
}

try {
checkAge(30);
checkAge(-1);
echo "This line never runs\n";
} catch (InvalidArgumentException $e) {
echo 'Caught: ' . $e->getMessage() . "\n";
}

checkAge(-5);

Step 2: Run It​

Terminal
php main.php
Output
Age 30 is fine
Caught: Age can't be negative: -1
PHP Fatal error: Uncaught InvalidArgumentException: Age can't be negative: -5 in /Users/Shared/you/main.php:8Stack trace:
#0 /Users/Shared/you/main.php(21): checkAge(-5)
#1 {main}
thrown in /Users/Shared/you/main.php on line 8

Fatal error: Uncaught InvalidArgumentException: Age can't be negative: -5 in /Users/Shared/you/main.php:8
Stack trace:
#0 /Users/Shared/you/main.php(21): checkAge(-5)
#1 {main}
thrown in /Users/Shared/you/main.php on line 8

A zsh terminal where php main.php prints Age 30 is fine and Caught: Age can't be negative: -1, then PHP Fatal error: Uncaught InvalidArgumentException with a stack trace, twice.

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

What Happened​

  • checkAge(30) ran to the end and printed its line.
  • checkAge(-1) threw. The rest of the function and the rest of the try block were skipped, so This line never runs never printed, and the catch block printed the message.
  • checkAge(-5) threw with nothing to catch it, so PHP stopped the script with Uncaught InvalidArgumentException. The stack trace shows where it was thrown, line 8, and the call that led there, checkAge(-5) on line 21.
  • The fatal error appears twice because this PHP's settings both display errors and log them to the terminal.

Common Mistakes​

MistakeWhat happensDo this instead
Writing throw InvalidArgumentException('...') without newPHP looks for a function by that name: Uncaught Error: Call to undefined function InvalidArgumentException()Write throw new ...
Catching a class the exception doesn't belong toThe catch is skipped and the exception goes on upCatch the class you throw, or a parent such as Exception
Throwing plain Exception for everythingCallers can't tell problems apartPick a specific class, such as InvalidArgumentException

Troubleshooting​

SymptomLikely causeFix
PHP Fatal error: Uncaught InvalidArgumentException: ...Nothing caught the exceptionWrap the call in try and catch
Uncaught Error: Call to undefined function InvalidArgumentException()new is missing after throwWrite throw new InvalidArgumentException(...)

FAQ​

Which exception class should I throw?​

PHP comes with several in its Standard PHP Library: InvalidArgumentException for a bad argument, UnexpectedValueException for a value that doesn't fit, RuntimeException for problems found while running. You can also extend Exception with classes of your own.

Can I throw from inside an expression?​

Yes. throw can stand where a value is expected, so $name = $input ?? throw new InvalidArgumentException('Name required'); throws when $input is null. With $input set to null, a catch around it caught Name required.

Conclusion​

throw new SomeException('...') stops a function and passes the problem up. Catch it where your code can do something about it, and let it end the script only when nothing can.

Additional Resources​