On Mon, Nov 27, 2017 at 5:06 AM, <encla...@safe-mail.net> wrote: > Greetings! > > I have been referred to this mailing list by > https://wiki.php.net/rfc/howto > as the first step to propose a language change. I first tried to register > on wiki.php.net as per php-src/README.SUBMITTING_PATCH in order to > actually > make an RFC, only to be given an error: > > Writing /srv/web-wiki/dokuwiki/conf/users.auth.php failed > > I am proposing a patch (see attachment) to bring C++-like > function-try-block > shorthand syntax (http://en.cppreference.com/w/cpp/language/function-try- > block) > for whole-function try-catch-finally blocks: > > function fuu($foo, $bar): void try > { > may_throw($foo); > may_throw($bar); > > } catch (FuuException $e) { > echo $e->getMessage(); > } > > Since PHP is partially influenced by C++, I believe this syntax would be > a meaningful step in making PHP a little bit more intuitively compatible > with C++ practices, which may prove useful for people who come to PHP from > the C++ world (such as myself.) The expected benefit is PHP becomes yet > more familiar and comfortable for C++ programmers. > > Also, this syntax saves us one set of curly braces and an indentation > level, > allowing for more compact and expressive functions, and especially > closures: > > $s = preg_replace($re, $s, function (array $m): void try { > return find_replacement(...$m); > } catch (Throwable $e) { > return $m[0]; > }); > > In addition to the syntactic sugar, I would like to outline another > possible > merit: the very fact of such a shorthand construct existing may encourage > programmers to write functions with a consistent approach to exception > handling > at whole-function level. Each such function becomes a self-contained code > unit > tightly coupled with its exception handling logic, the programmer's intent > clearly outlined by the use of the proposed construct, thereby facilitating > code clarity and integrity and promoting a stricter and more rigid code > style. > > The proposed patch makes purely cosmetic modifications to > zend_language_parser.y > grammar to augment plain functions, class methods, and closures to accept > try-catch-finally blocks as their bodies in addition to regular compound > statements. It amounts to just a handful of lines and entails no API > changes. > > I submitted my patch via the bugtracker: https://bugs.php.net/bug.php? > id=75576 > > Please share your thoughts. >
I believe that the reason why C++ has function-level try-catch blocks is that they provide the only way of catching exceptions thrown by the member initializer list of a constructor. As PHP does not have any such functionality, PHP has no need for function-level try-catch blocks. I doubt that C++ introduced these as a way to save a couple of braces, especially given that C++ does not allow the use of other, and arguably significantly more common, control-flow statements without an explicit function block. Nikita