With regards to when and when not to use typed throws there’s also a long and detailed historical post that drills down into specifics that largely arrives at the same conclusions reached in the proposal: in most cases it’s probably better to throw any Error
, but, reluctantly, it’s needed for certain use cases.
I feel the current proposal does a good job of summarising the cases where it’s needed. i.e. generic expressivity, embedded/real-time applications. But maybe could benefit from examples where you shouldn’t use typed throws. i.e. most places.
One particular use case that stood out for me as something that may benefit from highlighting as an anti-pattern was using typed throws to encode a makeshift call stack, i.e. creating a breadcrumb trail up the call-stack through the use of typed, nested errors.
Now, while this is a perfectly valid use case (having something akin to a stack trace to diagnose exactly where something might have gone awry is a useful thing) perhaps providing a lower friction community-blessed alternative (i.e. consistent across third party modules) would go someways to eliminating this potential anti-pattern.
How this would manifest, I don’t know. One option could be to include a Foundation Error type which does include a underlyingError: any Error?
property, or another could be something enabled by the runtime, maybe by some top-level annotation, which facilitates the accumulation of a stack trace equivalent up each of the ‘throw’ sites.
Something else that will help greatly with this is the approval of SE-0409: If a module imports a third-party module internally, they’ll be nudged when they accidentally ‘encode the dependency tree’ by including a third-party Error type as a part of their own public Error.
Now, all of this might sound a little prescriptive, but personally that’s something I appreciate in a language. It’s liberating to have one ‘blessed’ way of doing things rather than needing to learn dozens of equally clever alternatives. The smaller surface area is a boon to creativity.