Skip to content

Commit 66287ca

Browse files
committed
Add example of throws(E) vs rethrows
1 parent 2fe85ff commit 66287ca

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

TSPL.docc/ReferenceManual/Declarations.md

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1594,18 +1594,26 @@ and a throwing method can't satisfy a protocol requirement for a rethrowing meth
15941594
That said, a rethrowing method can override a throwing method,
15951595
and a rethrowing method can satisfy a protocol requirement for a throwing method.
15961596

1597-
<!-- XXX comparison between rethrows and generic typed throws
1597+
An alternative to rethrowing is throwing a specific error type in generic code.
1598+
For example:
15981599

1599-
func f<E: Error>(closure: () throws(E) -> Int) throws(E) -> Int { ... }
1600-
func g(closure: () throws -> Int) rethrows -> Int { ... }
1600+
```swift
1601+
func someFunction<E: Error>(callback: () throws(E) -> Void) throws(E) {
1602+
try callback()
1603+
}
1604+
```
16011605

1602-
map() from the stdlib is another example
1606+
This approach to propagating an error
1607+
preserves type information about the error.
1608+
However, unlike marking a function `rethrows`,
1609+
this approach doesn't prevent the function
1610+
from throwing an error of the same type.
16031611

1604-
XXX FROM DOUG
1605-
Part of me wants to suggest that this whole section be revised to replace rethrows entirely with the use of generic typed throws, because that's how I expect the language to go over time. Then, rethrows would become more of a historical anecdote. However, that is a lot of work, and perhaps we'll find that rethrows will remain for longer than I expect. If so, I think it's fine to keep this comparison short: take the someFunction example from the beginning of the section and make it generic over the thrown error type, and note that it's providing a more precise guarantee about what errors it rethrows than rethrows does (because rethrows always produces an any Error).
1606-
XXX END FROM DOUG
1612+
<!--
1613+
TODO: Revisit the comparison between rethrows and throws(E) above,
1614+
since it seems likely that the latter will generally replace the former.
16071615
1608-
Filed rdar://128972373
1616+
See also rdar://128972373
16091617
-->
16101618

16111619
### Asynchronous Functions and Methods

0 commit comments

Comments
 (0)