On 21-10-19 19:19, Mark Randall wrote:
> On 21/10/2019 17:02, Rowan Tommins wrote:
>> - They immediately jump control out of the current frame of execution.
>> Unless you put a separate "try-catch" around every line, there is no
>> "acknowledge and run next line".
> 
> I've been toying with the idea of:
> 
> $x = tryval fopen('missing.txt', 'r'),
>             FileException => null;
> 
> if ($x === null) {
>   die('File could not be opened.');
> }
> 

Or maybe introduce a try() function that can wrap calls. Since most - if
not all - functions would throw a single type of exception, the
following would catch that exception and return null in stead:

  $x = try(fopen('missing.txt', 'r'))

An optional argument could be used to return a different error value:

  $x = try(fopen('missing.txt', 'r'), false)

I guess that would cover most use cases and make it easier for people to
accept an RFC on this subject. For cases where a function can throw
multiple exceptions, the syntax could even be extended to allow this:

  $x = try(fopen('missing.txt', 'r'), [FileException => false])

Here, try() would swallow only FileException, other exceptions are still
thrown. I'm not sure if this construct is worth introducing though, the
difference compared to a proper try / catch is much smaller.

A try() function could also help provide a migration path to PHP 8. It
may be possible to write an automatic code fixer that wraps any function
calls that need it in a try() to retain old behavior. Backporting try()
to PHP 5.x would allow the same code to run on both PHP 5 and 8.


Regards,
Dik Takken

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to