Tuesday 8 June 2021

Php: How to throw an exception

‘throw’ keyword is used to throw an exception from a block of code.

 

Syntax

throw exception_object;

 

Example

throw new LogicException('Division by zero');

 

Following snippet calculate a/b, if b is 0, then it throws a LogicException.

function div($a, $b){
    if($b == 0){
        throw new LogicException('Division by zero');
    }
    return $a /$b;
}

 

Find the below working example.

 

throw_exception.php

#!/usr/bin/php

<?php 

    function div($a, $b){
        if($b == 0){
            throw new LogicException('Division by zero');
        }
        return $a /$b;
    }

   $result1 = div(10, 3);

   echo "\$result1: $result1\n";

   $result1 = div(10, 0);
    
?>

 

Output

$./throw_exception.php 

$result1: 3.3333333333333

Fatal error: Uncaught LogicException: Division by zero in /Users/krishna/eclipse-workspace/php_examples/exception_handling/throw_exception.php:7
Stack trace:
#0 /Users/krishna/php_examples/exception_handling/throw_exception.php(16): div(10, 0)
#1 {main}
  thrown in /Users/krishna/php_examples/exception_handling/throw_exception.php on line 7

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment