This is an old revision of the document!
PHP RFC: Catching Multiple Exception Types
- Version: 1.0
- Date: 2016-03-06
- Author: Pierrick Charron pierrick@php.net, Bronisław Białek after89@gmail.com
- Status: Draft
- First Published at: http://wiki.php.net/rfc/multiple-catch
Introduction
When two different types of exceptions are handled the same way, it is sometimes required to duplicate code of the catch statements.
For exemple :
<?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 introduce the possibility to catch multiple exceptions 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
Backward Incompatible Changes
None.
Proposed PHP Version(s)
7.1
RFC Impact
To SAPIs
None
To Existing Extensions
None
To Opcache
None
Links and Literature
Similar feature in Java: http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
Request on StackOverflow: http://stackoverflow.com/questions/8439581/catching-multiple-exception-types-in-one-catch-block
Proposed Voting Choices
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.