Swift Robustness & AsyncLesson 37Free preview
Swift Error Handling
This lesson is part of Swift · All levels
Summary
This lesson reviews Error Handling in Swift using the Error protocol, keyword 'throws', and do-catch constructs. Swift uses an explicit and controlled error handling model. The developer will learn the difference between using 'try', 'try?' (return Optional), and 'try!' (force execution).
Key points
- The error type is defined by adopting the 'Error' protocol (usually Enum)
- The function that potentially triggers the error is marked with the keyword 'throws'
- Calling a function that throws an error must start with the keyword 'try'
- Do-catch constructs that capture and handle errors in a structured manner
- The keyword 'defer' guarantees that the cleaning code block is always executed before it goes out of scope.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.