[swift-users] "business applications market" flame

Jeremy Pereira jeremy.j.pereira at googlemail.com
Thu Jan 7 03:45:58 CST 2016


> On 6 Jan 2016, at 20:15, Jens Alfke <jens at mooseyard.com> wrote:
> 
> 
>> On Jan 6, 2016, at 11:40 AM, Jeremy Pereira via swift-users <swift-users at 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. 

Absolutely and I think this is critical to successfully handling errors. In Java, there is compiler support for telling if a checked exception can happen at the call site (although you can’t tell just by looking at the line of code), but the callee can also throw a RuntimeException which is ignored by the compiler but can be caught if you want to catch it. This is a recipe for disaster much like propagating an Objective-C exception through a stack frame that is not exception safe. You cannot safely catch a RuntimeException because you do not know if functions higher up the chain properly cleaned up after themselves.

> 
> 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.

+1 million for the “too much trouble” bit. I’ve even seen Java libraries where the rule was that all exceptions have to be RuntimeExceptions so that the caller doesn’t have to bother with error checking. It’s a disaster.

> 
> * 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!

You are preaching to the choir. 


More information about the swift-users mailing list