/* ErroneousNumbers.swift (c) Kari Laitinen http://www.naturalprogramming.com 2018-01-02 File created. This program shows how to throw and catch Errors in Swift. */ import Foundation enum NumberError : Error { case too_small case too_large case not_given } func get_number_from_keyboard() throws -> Int { let optional_from_keyboard = Int( readLine()! ) guard optional_from_keyboard != nil else { throw NumberError.not_given } // Now we can be sure that a valid number was given. // Let's store the optional value to a normal variable // and throw some errors if necessary. let number_from_keyboard = optional_from_keyboard! guard number_from_keyboard > 99 else { throw NumberError.too_small } guard number_from_keyboard < 999 else { throw NumberError.too_large } return number_from_keyboard } func get_number() throws -> Int { var number_from_above_function = 1234 do { number_from_above_function = try get_number_from_keyboard() } catch NumberError.too_small { print( "\n NumberError.too_small caught. \n" ) } return number_from_above_function } // The main program begins. print( "\n Please, type in a number: ", terminator: "" ) do { let number_read_via_several_functions = try get_number() print( "\n The number from keyboard is : \( number_read_via_several_functions )\n" ) } catch NumberError.too_large { print( "\n NumberError.too_large caught. \n" ) } catch { // This block will catch NumberError.not_given print( "\n Some Error was caught. \n" ) }