Throw and handle an error
Represent a recoverable failure explicitly.
enum InputError: Error { case negative }
func square(_ value: Int) throws -> Int {
guard value >= 0 else { throw InputError.negative }
return value * value
}
do { print(try square(-2)) }
catch InputError.negative { print("Use a nonnegative number") }
catch { print(error) }How it works
throws communicates failure. try marks the operation at its call site, and do/catch chooses how to recover. guard handles invalid input before the main operation.
EXPECTED OUTPUT
Use a nonnegative number
Keep in mind
This example assumes small integers. Large multiplication can overflow.