PHP Throwing Exceptions


Introduction

Throwable interface is implemented by Error and Exception class. All predefined Error classes are inherited from Error class. Instance of corresponding Error class is thrown inside try block and processed inside appropriate catch block.

Throwing Error

Normal execution (when no exception is thrown within the try block) will continue after that last catch block defined in sequence.

Example

 Live Demo

<?php
function div($x, $y) {
   if (!$y) {
      throw new Exception('Division by zero.');
   }
return $x/$y;
}
try {
   echo div(10,5) . "
";    echo div(10,0) . "
"; } catch (Exception $e) {    echo 'Caught exception: ', $e->getMessage(), "
"; } // Continue execution echo "Execution continues
"; ?>

Output

Following output is displayed

2
Caught exception: Division by zero.
Execution continues

In following example, TypeError is thrown while executing a function because appropriate arguments are not passed to it. Corresponding error message is displayed

Example

 Live Demo

<?php
function add(int $num1, int $num2){
   return $num1 + $num2;
}
try {
   $value = add(1, 'one');
} catch (TypeError $e) {
   echo $e->getMessage(). "
"; } ?>

Output

Following output is displayed

Argument 2 passed to add() must be of the type integer, string given

SPL Exceptions

Standard PHP library contains predefined exceptions

LogicExceptionException that represents error in the program logic.
BadFunctionCallException Exception thrown if a callback refers to an undefined function or if some arguments are missing.
BadMethodCallException Exception thrown if a callback refers to an undefined method or if some arguments are missing.
DomainExceptionException thrown if a value does not adhere to a defined valid data domain.
InvalidArgumentException Exception thrown if an argument is not of the expected type.
LengthExceptionException thrown if a length is invalid.
OutOfRangeExceptionException thrown when an illegal index was requested.
RuntimeExceptionException thrown if an error which can only be found on runtime occurs.
OutOfBoundsExceptionException thrown if a value is not a valid key.
OverflowExceptionException thrown when adding an element to a full container.
RangeExceptionException thrown to indicate range errors during program execution. An arithmetic error other than under/overflow.
UnderflowExceptionException thrown when performing an invalid operation on an empty container, such as removing an element.
UnexpectedValueException Exception thrown if a value does not match with a set of values.

Following example shows OutOfBoundsException thrown when a key in PHP array is not found

Example

 Live Demo

<?php
$arr=array("one"=>1, "two"=>2,"three"=>3,"four"=>4);
$key="ten";
try{
   if (array_key_exists($key, $arr)==FALSE){
      throw new OutOfBoundsException("key not found");}
   else {
      echo $arr[$key];}
   }
   catch (OutOfBoundsException $e){
      echo $e->getMessage(). "
"; } ?>

Output

Following output is displayed

key not found

Updated on: 18-Sep-2020

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements