It will take about 5 minutes to finish reading this article.
In Swift, both the rethrows keyword and the throws keyword are used to modify functions and exception handling.
The difference, however, is that rethrows indicates that this function does not actively throw errors under normal circumstances, but that it accepts one or more closures that throw errors as arguments, and may then continue to pass those errors on to the caller.
It can be simply understood that throws allow possible exceptions to be handled by the function or method (e.g., with do-catch), whereas rethrows just passes the throws; the function itself doesn’t need to handle the exception.
The use of the rethrows keyword is often used for functions that take closure arguments that may throw errors. The following is a simple example of code that uses the rethrows keyword:
1 | enum MathError: Error { |
The calling code is as follows:
1 | let a = 10 |
In this example, we define a safeDivide(::) function to perform division of an integer, which will check if the denominator is zero. Then we define a processNumbers(_:using:) function that takes a closure argument to process two integers. This function is labeled rethrows because it does not actively throw errors, but may pass them on to the caller.