Thursday 25 June 2015

PHP 7: new to alpha 2... Throwables now supported

G'day:
Exception handling has kinda been improved some more in PHP 7 alpha 2. Yesterday I looked at EngineExceptions ("http://blog.adamcameron.me/2015/06/php-7-php-starts-to-play-catch-up-with.html"), and part of that was a lamentation that PHP 7 had not implemented the idea of a Throwable which one could catch. Well: now they have.

Here's an example:

// throwable_error.php

try {
    function takesInt(int $x){
        return true;
    }

    takesInt('not an int');
} catch (Exception $e){
    echo 'Exception caught<br>';
} catch (Throwable $t) {
    echo 'Throwable caught<br>';
} finally {
    echo 'In finally<br>';
}


On alpha 1, this would result in:

In finally

Fatal error: Uncaught TypeException: Argument 1 passed to takesInt() must be of the type integer, string given, called in D:\php\php.local\www\experiment\7\exceptionHandling\throwable_error.php on line 9 and defined in D:\php\php.local\www\experiment\7\exceptionHandling\throwable_error.php:5 Stack trace: #0 D:\php\php.local\www\experiment\7\exceptionHandling\throwable_error.php(9): takesInt('not an int') #1 {main} thrown in D:\php\php.local\www\experiment\7\exceptionHandling\throwable_error.php on line 5


Now on alpha 2, I get this:

Throwable caught
In finally


So that's all right.

The implementation is still a bit pants though. Consider this:

// throwable_warning.php

try {
    $result = 1 / 0;
} catch (Throwable $t) {
    echo 'Throwable caught';
} catch (Exception $e){
    echo 'Exception caught';
} finally {
    echo 'In finally<br>';
}

This results in:


Warning: Division by zero in D:\php\php.local\www\experiment\7\exceptionHandling\throwable_warning.php on line 5
In finally


Why? Because a warning is not a Throwable.

For. F***'s. Sake.

How do you manage to make this all seem so hard, PHP?

--
Adam