- 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
Exceptions and Error in PHP 7
In the earlier versions of PHP,we could handle only exceptions. It was not possible to handle errors. In the case of a Fatal Error,it used to halt the complete application or some part of the application. To overcome this problem, PHP 7 added the throwableinterface to handle both exceptions and errors.
Exception: Wherever a fatal and recoverable error occurs, PHP 7 throws an exception instead of halting the complete application or script execution.
Error: PHP 7 throwsTypeError, ArithmeticError, ParserError, and AssertionError,but the warnings and notice errors remain unchanged. Using the try/catch block, error instance can be caught, and now, the FatalErrors can throw an error instance. In PHP 7,a throwable interface is added to unite the two exception branches, Exception and Error, to implement the throwable.
Example
<?php class XYZ { public function Hello() { echo "class XYZ
"; } } try { $a = new XYZ(); $a->Hello(); $a = null; $a->Hello(); } catch (Error $e) { echo "Error occurred". PHP_EOL; echo $e->getMessage() . PHP_EOL ; echo "File: " . $e->getFile() . PHP_EOL; echo "Line: " . $e->getLine(). PHP_EOL; } echo "Continue the PHP code
"; ?>
Output
In the above program, we will get the following error −
class XYZ Error occurred Call to a member function Hello() on null File: /home/cg/root/9008538/main.php Line: 11 Continue with the PHP code
Note: In the above example, we call a method on a null object. The catch is used to handle the exception and then continue the PHP code.
Arithmetic Error
We will use the DivisionByZeroError of arithmetic error. But still, we will get the warning error on the division operator.
Example: arithmetic error
<?php $x = 10; $y = 0; try { $z = intdiv($x , $y); } catch (DivisionByZeroError $e) { echo "Error has occured
"; echo $e->getMessage() . PHP_EOL ; echo "File: " . $e->getFile() . PHP_EOL; echo "Line: " . $e->getLine(). PHP_EOL; } echo "$z
"; echo " continues with the PHP code
"; ?>
Output
The output for the above program will execute with the warning error −
Division by zero File: /home/cg/root/9008538/main.php Line: 5 continues with the PHP code
Note: In the above program, we catch and report theDivisionByZeroError insidetheintdiv() function.