Swift 2.2 try块的错误处理

Swift 2.2 error handling by try block

几天前我才开始学习Swift。在我的 Xcode 操场上,我有以下代码:

//: Playground - noun: a place where people can play

import UIKit

enum VendingMachineError: ErrorType {
    case InvalidSelection
    case InsufficientFunds(coinsNeeded: Int)
    case OutOfStock
}


func requestBeverage(code: Int, coins: Int) throws {
    guard code > 0 else  {
        throw VendingMachineError.InvalidSelection
    }
    if coins < 2 {
        throw VendingMachineError.InsufficientFunds(coinsNeeded: 3)
    }
    guard coins > 10 else {
        throw VendingMachineError.OutOfStock
    }

    print("everything went ok")
}



try requestBeverage(-1, coins: 4)
print("finished...")

如果我尝试 运行 它,什么也不会发生。但我希望打印 "finished..." 因为在我的逻辑中,它尝试做某事,失败,然后程序将继续....

那么问题来了,为什么程序不继续运行,如果出现错误,我如何用尽可能少的单词告诉代码继续运行?

提前致谢

你需要捕捉错误

... 

do {
  try requestBeverage(-1, coins: 4)
} catch {
  print(error)
}
print("finished...")

请参阅 Swift 语言指南中的 Error Handling

编辑:您可以将整个表达式写在一行中 ;-)

do { try requestBeverage(-1, coins: 4) } catch { print(error) }

您可以使用 do/catch:

单独捕获所有错误
do {
    try requestBeverage(-1, coins: 4)
} catch VendingMachineError.InvalidSelection {
    print("Invalid selection")
} catch VendingMachineError.OutOfStock {
    print("Out of stock")
} catch VendingMachineError.InsufficientFunds(let coinsNeeded) {
    print("You need \(coinsNeeded) more coins")
} catch {
    // an unknown error occured
}

print("finished...")

或者,如果您只关心是否抛出错误而不关心抛出哪个错误,则使用 try?

func requestSomeBeverage() {
    guard (try? requestBeverage(-1, coins: 4)) != nil else {
        print("An error has occured")
        return
    }
}

requestSomeBeverage()
print("finished...")

如果您绝对确定不会抛出错误,并且希望在它抛出时引发异常,请使用 try!(但在大多数情况下,不要):

try! requestBeverage(-1, coins: 4)
print("finished...")