> On Jan 6, 2016, at 11:40 AM, Jeremy Pereira via swift-users
> <swift-users@swift.org> wrote:
>
> In Swift, you throw errors, not exceptions. The word exception is (more or
> less) reserved for conditions that terminate the process.
>
> There are no unchecked errors but then why would you not want to handle an
> error condition if it occurs? Why would you not want to know that an API can
> throw an error?
The bigger point is that in Swift you always know at the call site whether
something can fail. That is, you can see the possible flows of control by
inspecting the code.
Consider this block of code:
{ foo(); bar(); endFoo(); }
If foo is called, will endFoo() also be called?
In C++/Java/C# it’s not possible to tell without doing extensive analysis of
the implementation of bar (and everything that bar calls), because bar might
throw an exception and derail this flow of control. (And worse, some later code
change far away might add an unchecked exception, making your analysis wrong!)
This then requires adding noise in the form of a ‘finally’ block or a helper
class implementing RAII, if it’s really important that endFoo be called. In a
lot of cases this is “too much trouble” so a lot of code gets left like above,
and will break some invariant if the endFoo call gets skipped.
In Swift you can be sure that, if this block is entered, all three functions
will be called. (Unless the process hits a fatal exception like an assertion
failure or bus error and exits.) If it’s possible for bar to fail, then
(a) the call to bar will have to be prefixed with ‘try’, which is a yellow flag
to the programmer noting the possibility*; and
(b) the block will have to be inside a `do … catch` block, in the same
function, to handle the error. An error in bar() can’t just abort the function
silently. Any cleanup that has to be done will be explicit.
—Jens
* The requirement of the ‘try’ prefix means that if a function that isn’t
failable later gets modified to be failable, every call site will now trigger a
compile error due to the missing ‘try’ keyword. This means the programmer who
made the change will have to go through the codebase and consider the
possibility of failure and adjust the call site accordingly. This is a really
good thing!
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users