Swift Error Handling
Error handling is the process of responding to and recovering from error conditions in a program. In Swift, errors are represented using the Error
protocol, which allows us to define our own error types.
Throwing and Handling Errors in Swift
Swift uses a throw
statement to throw an error and a do-catch
statement to handle errors.
1enum CustomError: Error { 2 case runtimeError(String) 3} 4 5func test() throws { 6 throw CustomError.runtimeError("This is a runtime error.") 7} 8 9do { 10 try test() 11} catch CustomError.runtimeError(let message) { 12 print(message) 13}
In the above example, we define a custom error type called CustomError
, which conforms to the Error
protocol. We also define a function called test()
that throws a CustomError
with a message.
We use a do-catch
statement to call the test()
function. If an error is thrown, we catch it and print the error message.
Handling Errors with Optional Values
In some cases, we might want to use a value if it is available and handle an error if it is not. In Swift, we can use optional values to achieve this.
1enum CustomError: Error { 2 case runtimeError(String) 3} 4 5func test() throws -> Int { 6 throw CustomError.runtimeError("This is a runtime error.") 7} 8 9if let value = try? test() { 10 print("The value is \(value).") 11} else { 12 print("An error occurred.") 13}
In the above example, we use the try?
keyword to call the test()
function. If an error is thrown, the result will be nil
. If a value is returned, we print the value.
Propagating Errors in Swift
In some cases, we might want to propagate an error to the calling function. In Swift, we can do this by marking the function with the throws
keyword.
1enum CustomError: Error { 2 case runtimeError(String) 3} 4 5func test() throws -> Int { 6 throw CustomError.runtimeError("This is a runtime error.") 7} 8 9func testWrapper() throws { 10 let value = try test() 11 print("The value is \(value).") 12}
In the above example, we define a function called testWrapper()
that calls the test()
function. We mark the test()
function with the throws
keyword to indicate that it can throw an error. If an error is thrown, it will be propagated to the testWrapper()
function.