PHP AssertionError

The AssertionError class is a subclass of the Error class in PHP. This exception is thrown when the assert() function evaluates to FALSE. The assert() function checks if a given assertion is true and throws an AssertionError if the condition fails.

Syntax

// PHP 5 and PHP 7
assert ( mixed $assertion [, string $description ] ) : bool

// PHP 7 only
assert ( mixed $assertion [, Throwable $exception ] ) : bool

Parameters

Parameter Description
assertion String or boolean expression to evaluate
description Failure message (deprecated from PHP 7.2)
exception Throwable object (PHP 7 only)
Note: To catch AssertionError exceptions, you must enable assert.exception=on in your php.ini configuration file.

Basic Example

Here's a simple example demonstrating how AssertionError is thrown when an assertion fails −

<?php
$a = 10;
$b = 20;

try {
    assert($a == $b, "Values are not equal");
    echo "Assertion passed";
} catch (AssertionError $e) {
    echo "AssertionError: " . $e->getMessage();
}
?>
AssertionError: Values are not equal

Using Throwable Exception (PHP 7+)

In PHP 7, you can pass a custom exception object instead of a string message −

<?php
$value = 5;

try {
    assert($value > 10, new InvalidArgumentException("Value must be greater than 10"));
    echo "Value is valid";
} catch (InvalidArgumentException $e) {
    echo "Custom Exception: " . $e->getMessage();
} catch (AssertionError $e) {
    echo "AssertionError: " . $e->getMessage();
}
?>
Custom Exception: Value must be greater than 10

Conclusion

AssertionError provides a clean way to handle failed assertions in PHP. Use it for debugging and validation purposes, but remember to configure assert.exception=on to catch these exceptions properly.

Updated on: 2026-03-15T09:23:56+05:30

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements