Exploring error handling
When you write apps, bear in mind that error conditions may happen, and error handling is how your app would respond to and recover from such conditions.
First, you create a type that conforms to Swift's Error
protocol, which lets this type be used for error handling. Enumerations are normally used, as you can specify associated values for different kinds of errors. When something unexpected happens, you can stop program execution by throwing an error. You use the throw
statement for this and provide an instance of the type conforming to the Error
protocol with the appropriate value. This allows you to see what went wrong.
Of course, it would be better if you could respond to an error without stopping your program. For this, you can use a do-catch
block, which looks like this:
do {
try expression1
statement1
} catch {
statement2
}
Here, you attempt to execute code in the do
block using the try...