PHP 7 new exception hierarchy

interface Throwable
    |- Exception implements Throwable
        |- ...
    |- Error implements Throwable
        |- TypeError extends Error
        |- ParseError extends Error
        |- ArithmeticError extends Error
            |- DivisionByZeroError extends ArithmeticError
        |- AssertionError extends Error

In the older versions PHP can not handle fatal error but using PHP7 we can handle fatal error rather than halting the execution.

Throwable interface has the following declared methods :

interface Throwable
{
    public function getMessage(): string;
    public function getCode(): int;
    public function getFile(): string;
    public function getLine(): int;
    public function getTrace(): array;
    public function getTraceAsString(): string;
    public function getPrevious(): Throwable;
    public function __toString(): string;
}

To catch Exception and Error object we can use throwable in try/catch block. That means  Throwable may be used in try/catch blocks to catch both Exception and Error objects but it would be good if you will use specific exception class according to the situation.

-> Explanation and use of  Error class.

Virtually all errors in PHP 5.x that were fatal errors or recoverable fatal errors now throw instances of Error in PHP 7.

Example: How to catch fatal error.

<?php
try{
    add();
}catch (Error $e) {
    echo $e->getMessage(). "\n";
}
?>

Above example will show the message  "Call to undefined function add()" for php7 and above version but in php5.x it will throw fatal error so that is big improvement of php7.

<?php
try{
  $obj = new People();//trying to create object of not existence class
}catch (Error $e) {
    echo $e->getMessage(). "\n";
}
?>

So in this example output will be "Class 'People' not found "

-> Explanation and use of  TypeError class.
There are three scenarios where a TypeError may be thrown.
1. The argument type being passed to a function does not match its corresponding declared parameter type.
2. Value being returned from a function does not match the declared function return type
3. An invalid number of arguments are passed to a built-in PHP function (strict mode only)


Example of first scenario :

<?php
function add(int $num1,int $num2)
{
    return $num1+$num2;
}

try{
    add(100,'b'); //Second parameter is string but it should be int.
}catch(TypeError $e){
    echo $e->getMessage();
    
}

If you will execute it then it will throw error like "Argument 2 passed to add() must be of the type integer, string given"

Example of 2nd scenario :

<?php
/**
 * If you want to use return type of the function then you need to
 * use declare (strict_types = 1); statement at the top of the file to  support return type
 * 
 */

declare (strict_types = 1); 
function add(int $num1,float $num2): int
{
    return $num1+$num2;
}

try{
    echo add(100,2.5);
}catch(TypeError $e){
    echo $e->getMessage();
    
}

If you try to execute this program then it will throw error like : Return value of add() must be of the type integer, float returned.
You have given return type of defined function add as an integer so if this function return other than integer then program will throw TypeError exception.

Now I am going to change the return type of above function from int to float then let see the result.

<?php
/**
 * If you want to use return type of the function then you need to
 * use declare (strict_types = 1); statement at the top of the file to support return type
 * 
 */
declare (strict_types = 1);
function add(int $num1,float $num2): float
{
    return $num1+$num2;
}

try{
    echo add(100,2.5);
}catch(TypeError $e){
    echo $e->getMessage();

}

Output of this program is : 102.5

Example of third scenario :

I am trying to explain this scenario with rand php in built function.As you know this function required only two parameters min and max. Now I am going to pass three parameters in this function without using strict_types.
<?php
try{
    echo rand(1,2,3);
}catch(TypeError $e){
    echo $e->getMessage();

}
If you try to run this program then it will throw error like : Warning: rand() expects exactly 2 parameters, 3 given in /opt/lampp/htdocs/testscript/php7/exception/typeerror.php on line 11.So this kind of error we can't show in front of the user.

So in the above example, exception  is not working so this program behave like php5.x version.So if you want to support TypeError exception then you need to add strict_types.

Use  strict_types.
<?php
declare (strict_types = 1);
try{
    echo rand(1,2,3);
}catch(TypeError $e){
    echo $e->getMessage();

}

If you try to run this program then it will show error like : rand() expects exactly 2 parameters, 3 given

One thought on “PHP 7 new exception hierarchy”

Comments are closed.