How to catch errors in Swift?
sobes.tech AI
Answer from AI
In Swift, errors are caught using an error handling system based on the keywords throw, throws, try, and the do-catch block.
-
Declaring functions that can throw errors: The keyword
throwsis used after the function parameters.enum DataError: Error { case emptyData case invalidFormat } func processData(input: String) throws -> String { guard !input.isEmpty else { throw DataError.emptyData // Throw an error } // ...data processing logic... if input == "invalid" { throw DataError.invalidFormat } return "Processed: \(input)" } -
Calling functions that can throw errors: The keyword
tryis used.do { // Error handling block let result = try processData(input: "valid data") print(result) // "Processed: valid data" } catch { // Error catching block print("An error occurred: \(error)") } -
Catching specific error types: In the
catchblock, you can specify a particular error type.do { let result = try processData(input: "") print(result) } catch DataError.emptyData { print("Data is empty, please provide input.") } catch DataError.invalidFormat { print("Data format is invalid.") } catch { // Catching any other errors print("An unexpected error occurred: \(error)") } -
deferblock: Executes just before exiting the current scope, regardless of whether an exception occurred or not. Often used for resource cleanup.func openFile(_ filename: String) throws -> String { // Assume this opens a file and returns its contents print("Opening file \(filename)") // ... opening logic ... defer { // This code runs before exiting the function, // even if an error occurs print("Closing file \(filename)") } // ... file processing ... if filename == "error.txt" { throw DataError.invalidFormat // Throw an error } return "File content" } do { let content = try openFile("data.txt") print(content) } catch { print("Error handling file: \(error)") } -
Optional
try?: Returns an optional value. If the function throws an error,try?returnsnil.let processedResult = try? processData(input: "") // processedResult will be nil let validResult = try? processData(input: "abc") // validResult will be an optional String with value "Processed: abc" -
Forced
try!: Used when you are sure that no error will occur. If an error does occur, the app will crash. Use with caution.// Use only if you are 100% sure the function will not throw an error let result = try! processData(input: "always valid input")
The do-catch system is a more explicit and safer way to handle errors compared to traditional exceptions in other languages, as it requires explicit declaration of functions that can throw errors (throws) and explicit handling of these errors when calling (try, do-catch).