Swift: rethrows
Rethrows allows us to forward a thrown error by a given function parameter
Introduction
rethrows
keyword is used when you write a function that has a parameter that is a throwing function. If a throwing function throws an error, then the mail function becomes a throwing function, but if the throwing function in parameter doesn’t throw an error anytime, the other function doesn’t become a throwing function.
In this and similar examples, rethrows
keyword can be very useful for us: When you're writing a method like map
, or a function that controls access to a resource like withUnsafePointer
, that means you can support the occasional throwing function without burdening your many non-throwing calls with a do-try-catch sequence or try!
keyword that's both unnecessary and misleading.
In this article, we dive deeper rethrows
keyword in Swift. If you want to learn about throwing functions, you can check out our article below:
Using rethrows
Rethrowing functions must have at least one throwing function parameter. Simply rethrows
is used as in the following function:
func rethrowingFunction(callback: () throws -> Void) rethrows {
try callback()
}
A rethrowing function can contain a throw
statement only inside a catch
clause. This lets you call the throwing function inside a do-catch statement and handle errors in the catch clause by throwing a different error.
func someFunction(callback: () throws -> Void) rethrows {
do {
try callback()
} catch {
throw SomeError.error
}
}
In addition, the catch
clause must handle only errors thrown by one of the rethrowing function’s throwing parameters. For example, the following is invalid because the catch clause cannot handle the error thrown by alwaysThrows()
method.
A throwing method can’t override a rethrowing method, and can’t satisfy a protocol requirement for a rethrowing method. So, a rethrowing method can override a throwing method, and a rethrowing method can satisfy a protocol requirement for a throwing method.
If you use throwing function in the parameter(s) of your rethrowing function, you must use try
keyword for calling the rethrowing function like this:
func alwaysThrows() throws {
throw SomeError.error
}
func neverThrows() {
print("I never throw an error.")
}
try someFunction(callback: alwaysThrows)
someFunction(callback: neverThrows)
Conclusion
I rarely use rethrows
keyword, but the fun part of programming is that there is more than one way to solve problems. So, the good thing about rethrows
is that it gives us more flexibility. I remember that before rethrows
keyword, I had to use two different versions of the same function.