Thursday, May 12, 2022

What are the differences between throws and rethrows in Swift?

Rethrowing Functions and Methods

                A function or method can be declared with the rethrows keyword to indicate that it throws an error only if one of it’s function parameters throws an error. These functions and methods are known as rethrowing functions and rethrowing methods. Rethrowing functions and methods must have at least one throwing function parameter.

In our understanding way as below:

Roughly speaking, rethrows is for functions which do not throw errors "on their own", but only "forward" errors from their function parameters.

Example:

In your case,


func throwCustomError(function:(String) throws -> ()) throws


denotes a function which can throw an error, even if called with a non-throwing argument, whereas



-------


func rethrowCustomError(function:(String) throws -> ()) rethrows


denotes a function which throws an error only if called with a throwing argument.


Roughly speaking, rethrows is for functions which do not throw errors "on their own", but only "forward" errors from their function parameters.

No comments:

Post a Comment