Skip to content

Commit 48abe17

Browse files
owenvbenrimmington
authored andcommitted
Add Proposal: Multi-Pattern Catch Clauses (#1084)
* Add Proposal: Multi-Pattern and Conditionally Compiled Catch Clauses * Refocus proposal to only include multi-pattern catches * Update proposals/NNNN-multi-pattern-catch-clauses.md Co-Authored-By: Ben Rimmington <[email protected]> * Update NNNN-multi-pattern-catch-clauses.md Co-authored-by: Ben Rimmington <[email protected]>
1 parent 0071419 commit 48abe17

File tree

1 file changed

+126
-0
lines changed

1 file changed

+126
-0
lines changed
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
# Multi-Pattern Catch Clauses
2+
3+
* Proposal: [SE-NNNN](NNNN-multi-pattern-catch-clauses.md)
4+
* Authors: [Owen Voorhees](https://github.com/owenv)
5+
* Review Manager: TBD
6+
* Status: **Awaiting review**
7+
* Implementation:
8+
- [apple/swift#27776](https://github.com/apple/swift/pull/27776)
9+
10+
## Introduction
11+
12+
Currently, each catch clause in a do-catch statement may only contain a single pattern and where clause. This is inconsistent with the behavior of cases in switch statements, which provide similar functionality. It also makes some error handling patterns awkward to express. This proposal extends the grammar of catch clauses to support a comma-separated list of patterns (with optional where clauses), resolving this inconsistency.
13+
14+
Swift-evolution thread: [Thread](https://forums.swift.org/t/multi-pattern-and-conditionally-compiled-catch-clauses/30246)
15+
16+
## Motivation
17+
18+
Currently, Swift only allows up to one pattern and where clause for each catch clause in a do-catch statement, so the following code snippet is not allowed:
19+
20+
```swift
21+
do {
22+
try performTask()
23+
} catch TaskError.someRecoverableError { // OK
24+
recover()
25+
} catch TaskError.someFailure(let msg),
26+
TaskError.anotherFailure(let msg) { // Not currently valid
27+
showMessage(msg)
28+
}
29+
```
30+
31+
Because the above snippet is not valid today, developers frequently end up duplicating code between catch clauses, or writing something like the following instead:
32+
33+
```swift
34+
do {
35+
try performTask()
36+
} catch let error as TaskError {
37+
switch error {
38+
case TaskError.someRecoverableError:
39+
recover()
40+
case TaskError.someFailure(let msg),
41+
TaskError.anotherFailure(let msg):
42+
showMessage(msg)
43+
}
44+
}
45+
```
46+
47+
Nesting the switch inside of the catch clause is awkward and defeats the purpose of supporting pattern matching in catch clauses. Splitting the code up into multiple catch clauses requires duplicating the body, which is also undesirable. Supporting a multi-pattern catch clause would allow for code which is both clearer and more concise.
48+
49+
## Proposed solution
50+
51+
Catch clauses should allow the user to specify a comma-separated list of patterns. If an error thrown at runtime in a do block matches any of the patterns in a corresponding catch clause, that catch clause's body should be executed. Similar to switch cases, a user should be able to bind a variable in all patterns of a catch clause and then use it in the body.
52+
53+
With this change, the code snippet from the motivation section is now valid:
54+
55+
```swift
56+
do {
57+
try performTask()
58+
} catch TaskError.someRecoverableError { // OK
59+
recover()
60+
} catch TaskError.someFailure(let msg),
61+
TaskError.anotherFailure(let msg) { // Also Allowed
62+
showMessage(msg)
63+
}
64+
```
65+
66+
Now, if `performTask` throws either `TaskError.someFailure("message")` or `TaskError.anotherFailure("message")`, the body of the second catch clause will be executed and `showMessage` will be called.
67+
68+
## Detailed design
69+
70+
### Grammar Changes
71+
72+
The revised catch clause grammar is as follows:
73+
74+
```
75+
catch-clauses -> catch-clause catch-clauses?
76+
77+
catch-clause -> 'catch' catch-item-list? code-block
78+
79+
catch-item-list -> catch-item |
80+
catch-item ',' catch-item-list
81+
82+
catch-item -> pattern where-clause? |
83+
where-clause
84+
```
85+
86+
Note: Expressions with trailing closures are not allowed in any of a catch clause's items to avoid parsing ambiguity. This differs from the behavior of switch cases.
87+
88+
### Semantics
89+
90+
If a catch clause has multiple patterns, then its body will be executed if a thrown error matches any one of those patterns, and has not already matched a pattern from a preceding catch clause. Similar to switch cases, catch clauses with multiple patterns may still contain value bindings. However, those bindings must have the same name and type in each pattern.
91+
92+
## Source compatibility
93+
94+
This proposal maintains source compatibility. It will only result in code compiling which was considered invalid by older compiler versions.
95+
96+
## Effect on ABI stability
97+
98+
This feature has no ABI impact.
99+
100+
## Effect on API resilience
101+
102+
This proposal does not introduce any new features which could become part of a public API.
103+
104+
## Alternatives considered
105+
106+
### Do nothing
107+
108+
This is a relatively minor addition to the language, and arguably would see rather limited usage. However, in the cases where it's needed, it helps the user avoid hard-to-maintain error handling code which either duplicates functionality or nests control flow statements in a confusing manner. This proposal also simplifies Swift's pattern matching model by unifying some of the semantics of switch and do-catch statements.
109+
110+
## Future Directions
111+
112+
There are a number of possible future directions which could increase the expressiveness of catch clauses.
113+
114+
### Implicit `$error` or `error` binding for all catch clauses
115+
116+
Currently, only catch clauses without a pattern have an implicit `error: Error` binding. However, there are some cases where it would be useful to have this binding in all catch clauses to make, for example, re-throwing errors easier. However, using `error` as the identifier for this binding would be a medium-to-large source-breaking change. Instead, we could continue the trend of compiler defined identifiers and use `$error`. `error` in empty catch clauses could then be deprecated and eventually removed in future language versions, a smaller source break.
117+
118+
This change was not included in this proposal because it is source-breaking and orthogonal. If there is interest in this feature, we should probably consider it as an independent improvement which deserves its own proposal.
119+
120+
### `fallthrough` support in catch clauses
121+
122+
Allowing `fallthrough` statements in catch clauses would further unify the semantics of switch cases and catches. However, it is currently undesirable for a number of reasons. First, it would be a source-breaking change for existing do-catch statements which trigger `fallthrough`s in an enclosing switch. Also, there is no historical precedent from other languages for supporting `fallthrough`s in catch statements, unlike switches. Finally, there have not yet been any identified examples of code which would benefit from this functionality.
123+
124+
### Conditional compilation blocks around catch clauses
125+
126+
An earlier draft of this proposal also added support for wrapping catch clauses in conditional compilation blocks, similar to the existing support for switch cases. This was removed in favor of keeping this proposal focused on a single topic, and leaving room for a more comprehensive redesign of conditional compilation in the future, as described in [https://forums.swift.org/t/allow-conditional-inclusion-of-elements-in-array-dictionary-literals/16171](https://forums.swift.org/t/allow-conditional-inclusion-of-elements-in-array-dictionary-literals/16171/29).

0 commit comments

Comments
 (0)