Swift — Error handling
Error handling is the process of responding to and recovering from error conditions in your program.
- Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime.
Representing and Throwing Errors
In Swift, errors are represented by values of types that conform to the Error protocol. This empty protocol indicates that a type can be used for error handling.
Ex.
enum MyCustomError: Error {
case invalidSelection
case invalidUse
…..
…
}
Throwing an error lets you indicate that something unexpected happened and the normal flow of execution can’t continue. You use a throw statement to throw an error.
Ex.
thorw MyCustomError.invalidUse
Function can throw error
func canThrowErrors() throws -> String
- Using guard let or if else or switch
guard item.count > 0 else {
Get iOS Dev’s stories in your inbox
Join Medium for free to get updates from this writer.
throw MyCustomError.invalidUse
}
Handling Errors
do {
try <#expression#>
<#statements#>
} catch <#pattern 1#> {
<#statements#>
} catch <#pattern 2#> where <#condition#> {
<#statements#>
} catch <#pattern 3#>, <#pattern 4#> where <#condition#> {
<#statements#>
} catch {
<#statements#>
}
Defer Actions
Unlike control-flow constructs like if and while, which let you control whether part of your code is executed or how many times it gets executed, defer controls when a piece of code is executed.
You use a defer block to write code that will be executed later, when your program reaches the end of the current scope.
You use a defer block to write code that will be executed later, when your program reaches the end of the current scope.









