Daniel Tull: Today I Learned

Errors can propogate out of a throwing function when they're not caught

Sunday, 17 May 2020

Inside a function marked with throws, you do not need to catch all errors in the do-catch block, because they will propogate out of this function call if they are not caught. This seems obvious with some thought, but I found it slightly surprising.

struct SomeError: Error {}

func throwingFunction() throws {
    do {
        try anotherThrowingFunction()
    } catch let someError as SomeError {
        print("Found some error:", someError)
    }
}

func anotherThrowingFunction() throws {
    throw SomeError()
}

try throwingFunction()

If throwingFunction here was not marked as throws, then Swift would obviously complain:

Errors thrown from here are not handled because the enclosing catch is not exhaustive