[swift-evolution] Proposal: Typed throws

Matthew Johnson matthew at anandabits.com
Fri Dec 4 13:35:05 CST 2015


> Beyond that, however, it has always been unclear to me what exactly programmers expect to do with this additional typing information on errors, besides pedantically copying it all over the place and feeling pleased.  Libraries can fail in a lot of different ways.  It’s inevitable that that set will grow in ways that neither the library’s authors nor its users are necessarily anticipating.  
> 
> So I continue to feel that the pattern of “recognize a few special cases and then be prepared to deal with other failures generically” is basically the right approach for ordinary error-handling in Swift, and I think it’s pretty well-served by the current design.

I am a big proponent of typed throws.  IMO error results are every bit as important a part of an API contract as success results.  Sometimes erasing type information is the right API contract and sometimes it is not.  I don’t think requiring type information to be erased is the right way to go.  It should be a choice the language allows library authors to make for themselves.

I have worked in many languages over the last 20 years and one complaint I have nearly always had is that documentation of error cases is quite poor.  This problem has been significant enough that I think it warrants a language solution.  Typed errors provide compiler-enforced documentation about what errors can arise from a call.  The value of this compiler-enforced documentation should not be underestimated.

If the language evolves to support typed errors I believe we would learn how and when it is best to provide specific error types and when to employ type erasure / generic errors.  The range of options would encourage thoughtful library authors to consider their approach carefully and likely lead to solutions that facilitate better error handling in code that uses the library.  

One idea that I think merits consideration is the approach Rust uses to translate lower level errors representing implementation details into higher level errors represented in the API contract at module boundaries.  A well-designed language feature along these lines would go a long way towards addressing the complexity of “previously unanticipated errors”, would provide compiler enforced documentation, and would allow library authors to present a well-defined contract for error conditions as well as success conditions.

I hope this at least begins to answer the question of what programmers might hope to achieve with additional typing information on errors.

Matthew


More information about the swift-evolution mailing list