rfc:multiple-catch

PHP RFC: Catching Multiple Exception Types

Introduction

When two different types of exceptions are handled the same way, it is sometimes required to duplicate the code of the catch statements.

For example :

<?php
 
try {
   // Some code...
} catch (ExceptionType1 $e) {
   // Code to handle the exception
} catch (ExceptionType2 $e) {
   // Same code to handle the exception
} catch (Exception $e) {
   // ...
}

A solution to fix this problem on the user level would be to implement a common interface for ExceptionType1 and ExceptionType2 and catch it. However, this is only possible when you control the exception hierarchy in your own code, but not possible when you don't control the code.

Proposal

This RFC introduces the possibility to catch multiple exception types in a single catch statement to avoid code duplication.

<?php
 
try {
   // Some code...
} catch (ExceptionType1 | ExceptionType2 $e) {
   // Code to handle the exception
} catch (\Exception $e) {
   // ...
}

This syntax and functionality is compatible with the Union types RFC proposed here : https://wiki.php.net/rfc/union_types

When is it useful ?

  • When a single method/function throw two different types of exceptions that you handle the same way;
  • When libraries are leaking their dependency's exceptions.

Backward Incompatible Changes

None.

Proposed PHP Version(s)

7.1

RFC Impact

To SAPIs

None

To Existing Extensions

None

To Opcache

None

To PHP tools/IDE

This change will require every PHP tools and IDE based on an AST parser to be modified to take this syntax change into account.

Vote

As this is a language change, a 2/3 majority is required. The vote is a straight Yes/No vote for accepting the RFC and merging the patch. Voting started on 2016-04-17 and will end on 2016-05-01.

Should milti-catch be added to PHP 7.1
Real name Yes No
bishop (bishop)  
blanchonvincent (blanchonvincent)  
bwoebi (bwoebi)  
colinodell (colinodell)  
danack (danack)  
daverandom (daverandom)  
davey (davey)  
derick (derick)  
dmitry (dmitry)  
francois (francois)  
galvao (galvao)  
guilhermeblanco (guilhermeblanco)  
hywan (hywan)  
jhdxr (jhdxr)  
jpauli (jpauli)  
jwage (jwage)  
kalle (kalle)  
klaussilveira (klaussilveira)  
laruence (laruence)  
lcobucci (lcobucci)  
leigh (leigh)  
levim (levim)  
lstrojny (lstrojny)  
marcio (marcio)  
mariano (mariano)  
mbeccati (mbeccati)  
mcmic (mcmic)  
mightyuhu (mightyuhu)  
mike (mike)  
ocramius (ocramius)  
patrickallaert (patrickallaert)  
pauloelr (pauloelr)  
pierrick (pierrick)  
pollita (pollita)  
ramsey (ramsey)  
rmf (rmf)  
sammyk (sammyk)  
santiagolizardo (santiagolizardo)  
stas (stas)  
svpernova09 (svpernova09)  
thorstenr (thorstenr)  
trowski (trowski)  
tyrael (tyrael)  
weierophinney (weierophinney)  
zeev (zeev)  
zimt (zimt)  
Final result: 40 6
This poll has been closed.

Patches and Tests

Implementation

rfc/multiple-catch.txt · Last modified: 2017/09/22 13:28 by 127.0.0.1