[swift-evolution] Remove Failable Initializers
brent at architechies.com
Fri Mar 4 19:18:57 CST 2016
>> 1. Exceptions are used to communicate unrecoverable bugs, like null dereferences, divide-by-zero, etc.
> This is really a matter of convention, and also more of a matter of terminology. For example, in Swift, they’re just errors rather than exceptions; i.e- there’s no strict indication of their severity, and like any good “exception” model it’s up to the developer if they want to throw an error onwards, silently hide it, do some recovery etc. If you wish to throw a minor error vs a severe one, then you use different error types and document what they represent.
> I’d also argue that a failable initialiser represents no less severe an issue than an error does, as the initialiser has still failed, and therefore created nothing usable, ultimately requiring some form of recovery (testing for nil, supplying a default etc.). It isn’t clear at all to me that these are different things, as both can be recoverable or unrecoverable depending upon which form you use it in (try? vs try! vs try/catch, or Foo() vs Foo()!).
This is emphatically not true. Swift represents unrecoverable bugs with precondition failures, not error throwing. Force unwrapping failures (the Swift equivalent of null dereferences), divide-by-zero, and so on are not failures you can catch in Swift. They cause your code to crash immediately with no hope of reviving it. The Swift compiler even optimizes your code *assuming* these things will crash, so if you were to somehow catch such an error, your app would likely not function correctly. At the very least, it would leak a bunch of objects because it had missed lots of releases.
If you never have before, please read the Error Handling Rationale design document (https://github.com/apple/swift/blob/master/docs/ErrorHandlingRationale.rst). It's long, but it explains exactly why Swift's error handling is designed the way it is. The "Kinds of error" section might be especially instructive, particularly in that it exists at all. Not all errors are created equal, and many of the ugliest parts of other languages' error systems stem from their failure to recognize that fact.
More information about the swift-evolution