Home Quizzes Leaderboard Competitions Learn Hire Us
About Contact
Log In Sign Up
Learn PHP Exception Handling

Exception Handling

⏱ 18 min read read
try / catch / finally:

try {

// risky code here

} catch (InvalidArgumentException $e) {

// handle specific exception

} catch (RuntimeException $e) {

// handle another type

} catch (Exception $e) {

// catch-all for any Exception

} finally {

// ALWAYS runs --- cleanup code here

}

Common Built-in Exceptions:

Exception --- base class for all exceptions

InvalidArgumentException --- bad argument value

OutOfRangeException --- index/offset out of valid range

RuntimeException --- error at runtime

LogicException --- errors in program logic

OverflowException --- container is full

UnderflowException --- container is empty

TypeError --- wrong type passed

ValueError --- right type, wrong value (PHP 8+)

DivisionByZeroError --- division or modulo by zero

Error --- base class for fatal errors (PHP 7+)

Throwable --- interface for both Error and Exception

Custom Exceptions:

class InsufficientFundsException extends RuntimeException {

public function \_\_construct(private float $shortfall) {

parent::\_\_construct(

"Insufficient funds. Need \${shortfall} more."

);

}

public function getShortfall(): float { return $this->shortfall; }

}

throw new InsufficientFundsException(4300.00);

PHP uses throw new ExceptionClass() --- not just throw new.

PHP 7+ introduced Error class for fatal errors (separate from
Exception).

Catch Throwable to catch BOTH Exception and Error.

PHP 8+ allows throw as an expression: $name = $input ?? throw new
Exception();
Code Example
<?php

// Custom exception

class InsufficientFundsException extends RuntimeException {

public function \_\_construct(private float $shortfall) {

parent::\_\_construct("Insufficient funds. Need \$$shortfall
more.");

}

public function getShortfall(): float { return $this->shortfall; }

}

$balance = 1000.0;

function withdraw(float $amount): void {

global $balance;

if ($amount > $balance) {

throw new InsufficientFundsException($amount - $balance);

}

$balance -= $amount;

echo "Withdrew $$amount. Balance: $$balance\n";

}

function riskyParse(string $text): void {

try {

if (!is_numeric($text)) {

throw new InvalidArgumentException("'$text' is not a number!");

}

$number = (int)$text;

if ($number === 0) {

throw new DivisionByZeroError("Cannot divide by zero!");

}

$result = intdiv(100, $number);

echo "100 / $number = $result\n";

} catch (InvalidArgumentException $e) {

echo $e->getMessage() . "\n";

} catch (DivisionByZeroError $e) {

echo $e->getMessage() . "\n";

} else {

// Note: PHP has no try...else like Python

} finally {

echo "--- done ---\n";

}

}

riskyParse("5"); // 100 / 5 = 20

riskyParse("0"); // Cannot divide by zero!

riskyParse("abc"); // 'abc' is not a number!

try {

withdraw(300); // OK

withdraw(5000); // throws

} catch (InsufficientFundsException $e) {

echo $e->getMessage() . "\n";

echo "Shortfall: " . $e->getShortfall() . "\n";

}

// PHP 8+ --- throw as expression

$name = "" ?: throw new InvalidArgumentException("Name cannot be
empty");

?>
← String Functions & Regular Expressions File Input & Output →

Log in to track your progress and earn badges as you complete lessons.

Log In to Track Progress