- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP AssertionError
Introduction
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 −
Syntax
for PHP 5 and PHP 7 assert ( mixed $assertion [, string $description ] ) : bool PHP 7 only assert ( mixed $assertion [, Throwable $exception ] ) : bool
Parameters
Sr.No | Parameter & Description |
---|---|
1 | assertion string or boolean expression |
2 | description failure mssage |
3 | exception (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.
Example
<?php $a=10; $b=20; try { if (assert($a == $b, "assert($a == $b) failed.")) { echo("assert($a == $b) was successful."); } } catch (AssertionError $e) { echo $e->getMessage(); } ?>
Output
This will produce following result −
assert(10 == 20) failed.