-
使用枚举来定义多种
error
情况,遵循Error
协议,并使用throw
抛出对应错误情况//Representing and Throwing Errors enum VendingMachineError:Error { case invalidSelection case insufficientFunds(coinsNeeded: Int) case outOfStock } throw VendingMachineError.insufficientFunds(coinsNeeded: 5)
-
使用guard配合抛出相应异常
//Propagating Errors Using Throwing Functions struct Item { var price: Int var count: Int } class VendingMachine { var inventory = [ "Candy Bar" : Item(price: 12, count: 7), "Chips" : Item(price: 10, count: 4), "Pretzels" : Item(price: 7, count: 11), ] var coinsDeposited = 0 func vend(itemNamed name: String) throws { guard let item = inventory[name] else { throw VendingMachineError.invalidSelection } guard item.count > 0 else { throw VendingMachineError.outOfStock } guard item.price <= coinsDeposited else { throw VendingMachineError.insufficientFunds(coinsNeeded: item.price - coinsDeposited) } coinsDeposited -= item.price var newItem = item newItem.count -= 1 inventory[name] = newItem print("Dispensing \(name)") } }
-
使用try传递异常
func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws { let snackName = favoriteSnacks[person] ?? "Candy Bar" try vendingMachine.vend(itemNamed: snackName) }
-
使用do+try执行带有抛出异常的方法,使用catch捕获异常并加以处理
var vendingMachine = VendingMachine.init() vendingMachine.coinsDeposited = 1 do { try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine) } catch VendingMachineError.invalidSelection { print("Invalid Selection.") } catch VendingMachineError.outOfStock { print("Out of Stock") } catch VendingMachineError.insufficientFunds(let coinNeeded) { print("Insufficient funds. Please insert an additional \(coinNeeded) coins") }
-
使用try?将返回变为可选
//Converting Error to Optional Values func somtThrowingFunction() throws -> Int { } let x = try? somtThrowingFunction() let y : Int? do { try y = try somtThrowingFunction() } catch { y = nil }
-
使用try?同意处理多种throw错误结果处理相同时的简写
func fetchData() -> Data? { if let data = try? fetchDataFromDisk() { return data } if let data = try? fetchDataFromSever() { return data } return nil }
-
使用try!确定不会错误时强制拆包
//Disabling Error Propagation let photo = try! loadImage(atPath: "./Resources/John Appleseed.jpg")
-
使用defer标记代码段保证无论是throw error还是break均会在defer出现的区域末尾执行代码段
//Specifying Cleanup Actions func processFile(filename: String) throws { if exists(filename) { let file = open(filename) defer { close(file) } while let line = try file.readline() { // Work with the file. } // close(file) is called here, at the end of the scope. } }
使用defer标记close操作,使需要在if段落末尾执行的close语句写在前面对应open,保证执行open就一定会执行close操作
-
一段代码
enum learningError: Error { case noMethod case noReading case noTool(toolName: String) } func iosDev(method: Bool, style: Bool, hasTool: Bool) throws{ guard method else { throw learningError.noMethod } guard style else { throw learningError.noReading } guard hasTool else { throw learningError.noTool(toolName: "noMacBook") } } do { try iosDev(method: true, style: true, hasTool: false) print("is cool") } catch learningError.noMethod { print("no method") } catch learningError.noReading { print("no reading") } catch learningError.noTool(let name) { print("no", name) } catch { //加入空catch关闭 //否则会报错:Errors thrown from here are not handled because the enclosing catch is not exhaustive } if let result = try?iosDev(method: false, style: true, hasTool: true) { print("success") } else{ print("failure") }
网友评论