RE: [PHP-DEV] [VOTE] Catching Multiple Exception Types
| From: | Zeev Suraski | Date: | Mon, 18 Apr 2016 14:05:46 +0000 |
| Subject: | RE: [PHP-DEV] [VOTE] Catching Multiple Exception Types | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-92412@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: Marco Pivetta [mailto:ocramius@gmail.com]
> Sent: Monday, April 18, 2016 4:41 PM
> To: Dan Ackroyd <danack@basereality.com>
> Cc: Bronisław Białek <after89@gmail.com>; PHP internals
> <internals@lists.php.net>
> Subject: Re: [PHP-DEV] [VOTE] Catching Multiple Exception Types
>
> Heya,
>
> I voted "NO" due to previous discussion. TL;DR: this is FAR off the 80/20 use-
> case for a language syntax change.
>
> C&P from my answer elsewhere:
>
> The following typical example is something REALLY rare, and requiring a
> parser change for it seems excessive:
>
> try {
> // ...
> } catch (InvalidArgumentException $e) {
> // same handling
> } catch (PDOException $e) {
> // same handling
> } catch (BadMethodCallException $e) {
> // same handling
> }
>
> These 3 exceptions usually result in separate handling anyway. If same
> handling is needed, you can as usual extract a private method (if you are in a
> class) and deal with it there:
>
> try {
> // ...
> } catch (InvalidArgumentException $e) {
> $this->sameHandling($e);
> } catch (PDOException $e) {
> $this->sameHandling($e);
> } catch (BadMethodCallException $e) {
> $this->sameHandling($e);
> }
>
> private function sameHandling(Throwable $caught)
> {
> // same handling
> }
>
> Still, even in this case, I'd flag it up in a code review, as same handling for 3
> different exception types generally (not always) means something is really
> wrong.
I voted 'yes', as I think that exception handling is one of the few cases where it would
make sense to have similar (or completely identical) handling for very different object types.
Emitting a meaningful error and cleaning up are likely to look very similar for potentially quite
different exception types.
The main thing that made me question whether it's truly necessary, is that the same can be said
about catch (Exception $e), which could handle all exception types in a generic way. But I think it
is not uncommon to have a situation where you'd want to group a certain number of known
exception types in one group, and either propagate other exceptions or handle them differently.
I do find this one quite harmless in terms of potential negative implications - so even if it's
not exceptionally useful (no pun intended) - it's fairly intuitive, simple in implementation
and doesn't have to deal with scalars. The generic union types RFC has much farther reaching
implications in terms of influencing how code is likely to get written in the future, and IMHO not
for the better.
Zeev