throws
in Swift 2 is just another way to return from a function/method. Because of its propagation semantics, it's not really "exceptions", which is probably a good change.- But unlike an
Either
orResult
return type,throws
in Swift 2 cannot communicate type information. - This sucks; and we will realize it sucks when we keep having to refer to documentation every time we call a function that
throws
to see what sort of errors we may have to handle. This is part of the problem that types solve; they are documentation, with compiler-enforced guarantees. - Arguments based on the clunkiness of pattern-matching on a
Result
type vs. the new syntax are not valid. Had the Swift team chosen to introduce a blessed stdlibResult
type, they could have introduced elegant syntax to handle it without requiring boilerplate; remember, everything related tothrows
is new syntax. - Yes, this would make versioning harder. Changing the types of errors you return changes the contract of an API, if you care about anyone actually handling errors from it. Yes, this sucks for people maintaining APIs. They will have to deal with it.
- Other counterarguments are based on, effectively, making it slightly harder to write bad code — to ignore errors, catch-all, or simply rethrow errors. But people will go to extraordinary lengths to write bad code. And type-checked exceptions make this no worse; you already have to write a catch-all
catch
in Swift 2 anyway. - Yes, a method that calls a bunch of other methods and rethrows all their errors could have an unwieldy signature. If that is distasteful, do some error handling or coalescing in your method, or just mark it as throwing
ErrorType
and we're no worse off than we are now.
In closing: tell me what types of errors I have to handle, please. I'd prefer a monadic standard-library-blessed Result
type, but throws
can work. Just tell me what to catch; tell me what might fail so I have some chance of recovering appropriately.
The following three documents helped me form and solidify my opinions…