PHP AssertionError

PHPServer Side ProgrammingProgramming


AssertionError class is a subclass of Error class. This type of error is thrown when assert() returns FALSE

assert() checks if given assertion is true or false, and throws AssertionError if it is false. The assert() function is defined as follows −


for PHP 5 and PHP 7
assert ( mixed $assertion [, string $description ] ) : bool
PHP 7 only
assert ( mixed $assertion [, Throwable $exception ] ) : bool


Sr.NoParameter & Description
string or boolean expression
failure mssage
3exception (for PHP 7 only)
throwable object

Since PHP 7.0, assert() is now a language construct and not a function. assertion parameter can now be an expression and second parameter is either an exception, or description. From PHP 7.2 onwards, string description emits E_DEPRECATED message. The AssertionError thrown by assert() will be sent to catch block only if assert.exception=on is enabled in php.ini.

AssertionError Example

In this example, we assert condition is true, try block executes normally. If it is false, AssertionError message will be displayed from catch block.


 Live Demo

try {
   if (assert($a == $b, "assert($a == $b) failed.")) {
      echo("assert($a == $b) was successful.");
} catch (AssertionError $e) {
   echo $e->getMessage();


This will produce following result −

assert(10 == 20) failed.
Updated on 21-Sep-2020 11:32:36