I was reading Apple's official swift language guide, in the Error Handling chapter, it says: "There are four ways to handle errors in Swift. You can propagate the error from a function to the code that calls that function, handle the error using a
do
-catch
statement, handle the error as an optional value, or assert that the error will not occur."What does the word "propagate" mean here?
Let's clarify this a bit. In the original quote, "propagate" is not a technical term. It just means to transmit, or pass on. But let's not get stuck on the meaning of the word. The quote talks about four ways to handle an error, and I think it's clearer to list examples:
1. Propagate:
function doSomething () throws {
…
let result = try calculateSomething () // since the error is not handled, it's propagated to the caller
…
}
2. Handle:
do {
…
let result = try calculateSomething () // the error is handled by the "catch" block
…
}
catch {
…
}
3. As optional:
let optionalResult = try? calculateSomething () // the actual error is discarded
if let result = optionalResult {
…
}
4. Assert:
let optionalResult = try! calculateSomething () // crashes on error