Handle Swift Errors with Do-Catch
Written by Team Kodeco
In Swift, errors are represented by values of types that conform to the Error
protocol. The do-catch
statement is used to handle errors in a controlled and predictable way. It allows you to specify a block of code that can throw an error and another block of code to handle the error if it’s thrown.
Here is an example of using the do-catch
statement to handle a simple error:
enum SimpleError: Error {
case somethingWentWrong
}
func doSomething() throws -> String {
if true {
throw SimpleError.somethingWentWrong
}
return "Success!"
}
do {
let result = try doSomething()
print(result)
} catch {
print("Error: \(error)")
}
In this example, the doSomething()
function is declared as a throwing
function, which means that it can throw errors.
The do-catch
statement is used so that if it’s thrown and the catch
block is executed, the error
parameter of the catch block contains the error that was thrown.
It’s also possible to catch specific error types by pattern matching on the error
parameter in the catch block:
do {
let result = try doSomething()
print(result)
} catch SimpleError.somethingWentWrong {
print("Something went wrong")
} catch let otherError {
print("Error: (otherError)")
}
In this example, the catch block for SimpleError.somethingWentWrong
will only be executed if the error thrown is of that specific type. If any other error is thrown, it will be caught by the second catch block and the otherError
constant will be set to the error.
It’s also possible to use multiple catch blocks to handle different error types or to handle errors in different ways depending on their specific type or value.
It’s important to note that using the try?
or try!
versions of the try
keyword can also be used to handle errors, but the do-catch
statement provides more control and flexibility in handling errors.
It’s best practice to always use the do-catch
statement when working with throwing functions in Swift.