Friday, 11 June 2021

Php: try and multiple catch statements

If the code in try block throws different kinds of exceptions, you can

Use multiple catch blocks different types of exceptions.

 

Example

try{
    div(10, '0');
}catch(LogicException $e){
    echo "LogicException Occurred : " . ($e -> getMessage()) . "\n";
}catch(RuntimeException $e){
    echo "RuntimeException Occurred : " . ($e -> getMessage()) . "\n";
}

 

Always catch more specific exceptions first followed by generic exceptions.

 

Find the below working example.

 

handle_multiple_exceptions.php

#!/usr/bin/php

<?php 

    function div($a, $b){
        if(!is_int($a) || !is_int($b)){
            throw new RuntimeException("This operation supported only for integers");
        }
        
        if($b == 0){
            throw new LogicException('Division by zero');
        }
        return $a /$b;
    }

    try{
        div(10, '0');
    }catch(LogicException $e){
        echo "LogicException Occurred : " . ($e -> getMessage()) . "\n";
    }catch(RuntimeException $e){
        echo "RuntimeException Occurred : " . ($e -> getMessage()) . "\n";
    }
    
?>

 

Output

$./handle_multiple_exceptions.php 

RuntimeException Occurred : This operation supported only for integers

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment