[swift-evolution] typed throws
Johannes Weiß
johannesweiss at apple.com
Fri Aug 18 09:10:31 CDT 2017
Hi John,
tl;dr I think throws should be optionally typed. Ie. `func someSyscall(...) throws(POSIXError) -> Int` should be just as legal as `func doSomeFancyCocoaOperation() throws -> Void`.
> [...]
>> Here is where I think things stand on it:
>> - There is consensus that untyped throws is the right thing for a large scale API like Cocoa. NSError is effectively proven here. Even if typed throws is introduced, Apple is unlikely to adopt it in their APIs for this reason.
>> - There is consensus that untyped throws is the right default for people to reach for for public package (#2).
>> - There is consensus that Java and other systems that encourage lists of throws error types lead to problematic APIs for a variety of reasons.
>> - There is disagreement about whether internal APIs (#3) should use it. It seems perfect to be able to write exhaustive catches in this situation, since everything in knowable. OTOH, this could encourage abuse of error handling in cases where you really should return an enum instead of using throws.
>> - Some people are concerned that introducing typed throws would cause people to reach for it instead of using untyped throws for public package APIs.
>
> Even for non-public code. The only practical merit of typed throws I have ever seen someone demonstrate is that it would let them use contextual lookup in a throw or catch. People always say "I'll be able to exhaustively switch over my errors", and then I ask them to show me where they want to do that, and they show me something that just logs the error, which of course does not require typed throws. Every. Single. Time.
I just grep'ed through some code and what I always see is this:
} catch let e {
fatalError("unexcepted error caught: \(e)")
}
most of the code is fairly low-level and the only error thrown in there is a POSIXError which basically holds the errno value and a string describing the failed syscall. I find this a very common pattern. Also the IMHO quite widespread use of Result<E, T> types shows that there are valid uses of a typed error mechanism. On the other hand requiring a high-level Cocoa method to declare all errors doesn't seem right either. So why not optionally typing the throws?
> [...]
-- Johannes
More information about the swift-evolution
mailing list