如何在Swift中打印'catch all'异常的详细信息?

时间:2015-07-11 01:37:01

标签: ios swift swift2

我正在更新我的代码以使用Swift,我想知道如何打印与“catch all”子句匹配的异常的错误详细信息。我稍微修改了此Swift Language Guide Page中的示例以说明我的观点:

do {
    try vend(itemNamed: "Candy Bar")
    // Enjoy delicious snack
} catch VendingMachineError.InvalidSelection {
    print("Invalid Selection.")
} catch VendingMachineError.OutOfStock {
    print("Out of Stock.")
} catch VendingMachineError.InsufficientFunds(let amountRequired) {
    print("Insufficient funds. Please insert an additional $\(amountRequired).")
} catch {
    // HOW DO I PRINT OUT INFORMATION ABOUT THE ERROR HERE?
}

如果我发现意外的异常,我需要能够记录导致它的原因。

2 个答案:

答案 0 :(得分:109)

我只是想通了。我在Swift文档中注意到这一行:

  

如果catch子句未指定模式,则该子句将匹配并将任何错误绑定到名为error的本地常量

所以,我试过这个:

this.listenTo(this.collection,'remove',this.render);

它给了我一个很好的描述。

答案 1 :(得分:41)

来自 Swift编程语言

  

如果error子句未指定模式,则该子句将匹配并将任何错误绑定到名为let error的本地常量。

也就是说,catch子句中存在隐式do { // … } catch { print("caught: \(error)") }

let constant_name

或者,似乎error也是一个有效模式,因此您可以使用它来重命名错误常量(如果名称do { // … } catch let myError { print("caught: \(myError)") } 已在使用中,这可能会很方便):< / p>

{{1}}