PHP Exception Handling with Multiple catch blocks


Introduction

PHP allows a series of catch blocks following a try block to handle different exception cases. Various catch blocks may be employed to handle predefined exceptions and errors as well as user defined exceptions.

Example

Following example uses catch blocks to process DivisioByZeroError, TypeError, ArgumentCountError and InvalidArgumentException conditions. There is also a catch block to handle general Exception.

Example

 Live Demo

<?php
declare(strict_types=1);
function divide(int $a, int $b) : int {
   return $a / $b;
}
$a=10;
$b=0;
try{
   if (!$b) {
      throw new DivisionByZeroError('Division by zero.');}
      if (is_int($a)==FALSE || is_int($b)==FALSE)
         throw new InvalidArgumentException("Invalid type of arguments");
         $result=divide($a, $b);
         echo $result;
      }
      catch (TypeError $x)//if argument types not matching{
         echo $x->getMessage();
   }
   catch (DivisionByZeroError $y) //if denominator is 0{
      echo $y->getMessage();
}
catch (ArgumentCountError $z) //if no.of arguments not equal to 2{
   echo $z->getMessage();
}
catch (InvalidArgumentException $i) //if argument types not matching{
   echo $i->getMessage();
}
catch (Exception $ex) // any uncaught exception{
   echo $ex->getMessage();
}
?>

Output

To begin with, since denominator is 0, Divide by 0 error will be displayed

Division by 0

Set $b=3 which will cause TypeError because divide function is expected to return integer but dividion results in float

Return value of divide() must be of the type integer, float returned

If just one variable is passed to divide function by changing $res=divide($a); this will result ArgumentCountError

Too few arguments to function divide(), 1 passed in C:\xampp\php\test1.php on line 13 and exactly 2 expected

If one of arguments is not integer, it is a case of InvalidArgumentException

Invalid type of arguments

Updated on: 18-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements