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.
Engineering @ SadaPay
7 个月So, previously in Swift, you could say that a method throws something but not tell what it throws exactly? ??
Software Engineer, x-SadaPay
7 个月Nice write up Shoaib Akhtar Bhai ??
iOS Engineer, x-SadaPay
7 个月This is super stuff ?? Thanks for sharing ??