Exceptions and Error in PHP 7

PHPServer Side ProgrammingProgramming

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

Live Demo

<?php
   class XYZ {
      public function Hello() {
         echo "class XYZ\n";
      }
   }
   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\n";
?>

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

Live Demo

<?php
   $x = 10;
   $y = 0;
   try {
      $z = intdiv($x , $y);
   }
   catch (DivisionByZeroError $e) {
      echo "Error has occured\n";
      echo $e->getMessage() . PHP_EOL ;
      echo "File: " . $e->getFile() . PHP_EOL;
      echo "Line: " . $e->getLine(). PHP_EOL;
   }
   echo "$z \n";
   echo " continues with the PHP code\n";
?>

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.

raja
Published on 13-Mar-2021 11:27:36
Advertisements