3 ms·
Typed throws (of errors, swift does not support exceptions) are for pretty specific usage scenarios - there was a years-long recurring discussion around adding
by dwaite 2y ago
Typed throws (of errors, swift does not support exceptions) are for pretty specific usage scenarios - there was a years-long recurring discussion around adding them to the language (which I was an opponent).
They are useful within your own module, e.g. when they aren't part of an exported API, as an alternative to other error handling methods.
You can support them in generic utility methods like map, because you will just rethrow the typed throw.
Otherwise, it is meant for systems programming or use in embedded environments - basically the 'leaf code' that doesn't have upstream variability or independent upstream dependencies. It is meant to indicate things like 'errno' in a POSIX API. I actually feel it is a poor functional fit there; the valid error results differ both across errno-setting functions and across UNIX implementations of a particular function. The symbolic assignment (semantic error code to errno numeric value) is also variable across implementations. However, this allows the compiler to know errors are an int-sized stack type, vs a witness of a heap-allocated object.
To look at it differently, errors are meant either for recovery or for indicating a general failure for code to attempt to clean up from. Once you delegate an error to other code by rethrowing it, you no longer are conveying proper knowledge for recovery - so there's no purpose to having it be typed; all you can really do is try to fail gracefully.
A specific example - something like Swift Data is a poor fit for typed throws, because the database layer itself is adaptable. My Application doesn't know whether a failure is due to the local disk being out of space or a transient network issue connecting to a remote server, and attempting to recover from these in my application code is a pretty bad pattern because I'm baking in assumptions about a particular configuration of Swift Data across my application code (or into applications which use my module).
My opposition to the feature is that it is never required (you can indicate failure in the return signature via something like Result), adds overall language complexity, and is likely to be misused in cases where it doesn't provide value - it just adds ABI complexity over simply documenting expected Error types.