The Wait is Over: Typed Throws in Swift

The Wait is Over: Typed Throws in Swift

I've always found error handling in Swift to be challenging. In Swift, errors are represented by values of types that conform to the Error protocol. While this protocol indicates a type can be used for error handling, it's too generic and lacks readability.

The code above has several issues:

? Uncertainty: Callers might not know the exact types of errors to expect, making error handling less predictable.

?? Verbose Handling: More type-checking in catch blocks might be required to handle different error types appropriately.


Swift has finally introduced typed throws, which represents a notable improvement in its approach to error handling. 0413-typed-throws

This code has the following improvements:

?? Predictability: Typed throws specify which errors a function might throw, enhancing error handling predictability.

?? Compile-time Safety: By enforcing specified errors, typed throws reduce unexpected runtime issues, promoting code reliability.

?? Clarity and Readability: Including potential errors in the function signature enhances code self-documentation, aiding developer understanding.

?? Better Maintenance: Updating function signatures for new error types ensures consistent error handling across the codebase, improving maintainability.


While there are cases where throws are useful for error handling, in my experience, I've eagerly awaited the introduction of typed throws as it consistently leads to cleaner code.

Owais Bin Asad

Engineering @ SadaPay

7 个月

So, previously in Swift, you could say that a method throws something but not tell what it throws exactly? ??

Ayesha Waheed

Software Engineer, x-SadaPay

7 个月

Nice write up Shoaib Akhtar Bhai ??

回复
Junaid Khan

iOS Engineer, x-SadaPay

7 个月

This is super stuff ?? Thanks for sharing ??

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了