Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

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

LogicException Exception 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.
DomainException Exception 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.
LengthException Exception thrown if a length is invalid.
OutOfRangeException Exception thrown when an illegal index was requested.
RuntimeException Exception thrown if an error which can only be found on runtime occurs.
OutOfBoundsException Exception thrown if a value is not a valid key.
OverflowException Exception thrown when adding an element to a full container.
RangeException Exception thrown to indicate range errors during program execution. An arithmetic error other than under/overflow.
UnderflowException Exception 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: 2020-09-18T09:10:58+05:30

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements