try await and error propagation
Use try await with throwing async functions, handle failures with do/catch , and propagate errors up cleanly (including CancellationError ).
Why try await?
try await calls a throwing async function. If it throws, the error propagates unless you catch it. You can also use try? to convert to Optional.
Throwing async + do/catch
Create a throwing async function and call it with try await inside do/catch to handle failures.
enum NetError: Error { case offline; case badStatus(Int) }
func fetchNumber(from ok: Bool) async throws -> Int {
try await Task.sleep(nanoseconds: 100_000_000)
if !ok { throw NetError.offline }
return 7
}
Task {
do {
let n = try await fetchNumber(from: true)
print("value:", n) // 7
} catch {
print("failed:", error) // handled here
}
}All lessons in this course
- Structured concurrency, async functions
- async let, Task, cancellation
- try await and error propagation