美文网首页
Swift:Errors thrown from here ar

Swift:Errors thrown from here ar

作者: Magician | 来源:发表于2016-12-21 16:27 被阅读826次

在学习 Swift 错误处理的时候,官方给出的 do-catch 例子如下:

...
...

let favoriteSnacks = [
    "Alice": "Chips",
    "Bob": "Licorice",
    "Eve": "Pretzels",
]
func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
    let snackName = favoriteSnacks[person] ?? "Candy Bar"
    try vendingMachine.vend(itemNamed: snackName)
}

var vendingMachine = VendingMachine()
vendingMachine.coinsDeposited = 8
do {
    try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine)
} catch VendingMachineError.invalidSelection {
    print("Invalid Selection.")
} catch VendingMachineError.outOfStock {
    print("Out of Stock.")
} catch VendingMachineError.insufficientFunds(let coinsNeeded) {
    print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.")
}
// Prints "Insufficient funds. Please insert an additional 2 coins."

但是亲自上手敲代码的时候,却总是在 "do" 闭包中 try 语句上报错:

"Errors thrown from here are not handled because the enclosing catch is not exhaustive"

1.png

大体意思是说这个 do-catch 是不完整的。这时候需要再加上一个空的 catch 语句用于关闭 catch。

do {
    try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine)
} catch VendingMachineError.invalidSelection {
    print("Invalid Selection.")
} catch VendingMachineError.outOfStock {
    print("Out of Stock.")
} catch VendingMachineError.insufficientFunds(let coinsNeeded) {
    print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.")
} catch { // 加入一个空的catch,用于关闭catch。否则会报错:Errors thrown from here are not handled because the enclosing catch is not exhaustive

}

相关文章

  • Swift:Errors thrown from here ar

    在学习 Swift 错误处理的时候,官方给出的 do-catch 例子如下: 但是亲自上手敲代码的时候,却总是在 ...

  • errors thrown from here are not

    缺少空白catch 现象 使用try时出现如下错误 errors thrown from here are not...

  • Value for SWIFT_VERSION cannot b

    Xcode 报错 Showing All Errors Only Value for SWIFT_VERSION ...

  • From Here to Eternity

    一月十四日的晚上,我正赶一篇第二天到死线的essay,播放器里循环了一晚的莫扎特K331也救不了异常暴躁的神经和牙...

  • Start from here

    最近突然有读英国作品的念头,不敢相信这是一个月前还抱着《剩者为王》每天打卡写心得的自己。于是列出暑假书单,《8...

  • Start From Here

    I don't care where I go.

  • Start from here

    春节窝在家没出门,舒舒服服躺了7天。今天因为要接人,迫不得已,要揭开小破车的封印了。 照例先热车半分钟,踩刹车、上...

  • start from here

    今天下载了“两书”:简书和小红书。简书是一直想下载的软件,看到朋友在上面写了东西,洋洋洒洒记录着生活、心情和感悟,...

  • start from here

    依然是忙碌的一天 下班时大领导约谈,工作上的发展空间沟通 感觉自己有点分裂 一方面想工作上拼一下,按照社会常规的定...

  • Swift Errors

    fatal error: unexpectedly found nil while unwrapping an O...

网友评论

      本文标题:Swift:Errors thrown from here ar

      本文链接:https://www.haomeiwen.com/subject/tuvqvttx.html