Introduction
We use do-try-catch to safely run code that might fail. It helps us handle errors without crashing the program.
We use do-try-catch to safely run code that might fail. It helps us handle errors without crashing the program.
do {
try someFunctionThatThrows()
// code if no error
} catch {
// code to handle error
}do starts a block where errors can be caught.
try is used before a function that can throw an error.
do {
try readFile()
print("File read successfully")
} catch {
print("Failed to read file")
}do {
try convertInputToNumber()
print("Conversion succeeded")
} catch {
print("Conversion failed")
}This program checks if a number is negative. If it is, it throws an error. The do-try-catch block catches the error and prints a message.
import Foundation enum SimpleError: Error { case badNumber } func checkNumber(_ number: Int) throws { if number < 0 { throw SimpleError.badNumber } } do { try checkNumber(-5) print("Number is good") } catch { print("Caught an error: number is negative") }
You must use try before calling a function that can throw an error.
The catch block runs only if an error happens inside do.
You can have multiple catch blocks to handle different errors.
Use do-try-catch to handle errors safely.
try marks code that might fail.
catch handles errors without crashing.
do-try-catch in Swift?do-try-catchdo-try-catch block in Swift?do-try-catch syntaxdo {}, inside which try is used before the function that might throw.do block, uses try inside, and follows with catch block.enum MyError: Error { case fail }
func risky() throws {
throw MyError.fail
}
do {
try risky()
print("Success")
} catch {
print("Caught an error")
}risky()MyError.fail.do-try-catch blocktry risky() runs, it throws an error, so the code jumps to the catch block and prints "Caught an error".do {
try someFunction()
} catch error {
print("Error: \(error)")
}
func someFunction() {
print("Running")
}someFunction() is called with try, so it must be declared with throws to indicate it can throw errors.someFunction() is not marked throws, the compiler will raise an error.enum FileError: Error { case notFound, unreadable }
func readFile(_ name: String) throws -> String {
if name == "missing.txt" { throw FileError.notFound }
if name == "bad.txt" { throw FileError.unreadable }
return "File content"
}
do {
let content = try readFile("bad.txt")
print(content)
} catch FileError.notFound {
print("File not found")
} catch {
print("Other error")
}readFile("bad.txt") throws FileError.unreadable.FileError.notFound, which does not match. The second catch is a general catch that handles all other errors, so it runs and prints "Other error".Pass the test and this pattern moves unknown