Chapter 6. Effortless error handling

 

This chapter covers

  • Error-handling best practices (and downsides)
  • Keeping your application in a proper state when throwing
  • How errors are propagated
  • Adding information for customer-facing applications (and for troubleshooting)
  • Bridging to NSError
  • Making APIs easier to use without harming the integrity of an application

Error handling is an integral part of any software development and not Swift-centric. But how Swift treats error handling does impact the way you deliver code that is pleasant to use and respects problems that can arise in a system. In this chapter, you’ll elegantly throw and catch errors while walking the fine line between creating a useful API instead of a tedious one.

Error handling sounds simple in theory: throw some errors and catch them, and your program keeps running. But in reality, doing it correctly can get quite tricky. Swift also adds a unique flavor on top where it imposes rules, offers syntactic sugar, and compile-time checks to make sure you’re handling thrown errors.

Even though it’s a start to throw an error when something goes wrong, there are many subtleties. Moreover, once you do end up with an error, you need to know where the responsibility lies to handle (or ignore) the error. Do you propagate an error all the way up to the user, or can your program prevent errors altogether? Also, when exactly do you throw errors?

6.1. Errors in Swift

6.2. Error propagation and catching

6.3. Delivering pleasant APIs

6.4. Closing thoughts

Summary

Answers

sitemap