Error Handling Summary in Swift
In short words, error handling is a safe guard for our code that handle unexpected situation during in the execution of a program that may crash and terminate the app from running.
In Swift, there are 4 ways to handle error:
- Propagate the error from function to calling code
- Using a do-catch statement
- Handle the error as an optional value
- Disabling error propagation
Lets define a custom error type. In Swift, errors are value type and conformed to the Error protocol.
1. Propagate the error from function to calling code
Lets define a throwing function. A throwing function is a function marked with keyword throws, it doesn’t handle the error itself rather propagate the error to calling scope.
throws keyword need to place after function parameter and before return type.
Here sampleThrowError() function is called a throwing function because it can throw error, it doesn’t handle error itself and the error must be handled by calling scope.
2. Using a do-catch statement
The error throwing function should be called within do block and a try keyword. Catch can handle particular error as well as any error when no argument provided.
3. Handle the error as an optional value
Here try? is used to handle the error. If any error occurs the result of the expression will be nil in other case the actual result will return. In the following example, str will be nil.
4. Disabling error propagation
If a calling function can throw error, and if we are sure that the error will not occur, then we can disable the error propagation by try! keyword. For example, we load and image file in code and the image will be provided with the app, so there is no chance the error occur. Another example, lets define a function:
This throwing function throws an error when val = 5.
But if we send a value other than 5, it will never throws an error which we are sure. So we can disable error propagation
But if we send val = 5, we will get a fatal error unless we handle the error within do-catch block.
Cleanup actions using defer
Well in Java language, one of there error handling way is try-catch-finally. Swift’s do-catch is almost similar like try-catch but swift define finally in another way which is called defer statement.
If you define finally block in Java, the finally block must be placed at the end of a catch block.
In swift, defer is not work like that way. You can write defer block in any place in a scope, and it will call before leaving the scope, whether in the scope any error occurred or not.
For example we define a function, at a point it throws an error. But if we test, we see the defer works by emptying the string. As a rule, defer works at the last moment before leaving the scope. So in this case defer will call after error thrown.
Useful iOS and Swift Books: