Ios 如何打印&x27的详细信息;一网打尽';Swift中的例外情况?
我正在更新代码以使用Swift,我想知道如何打印与“catch all”子句匹配的异常的错误详细信息。为了说明我的观点,我稍微修改了这个例子:Ios 如何打印&x27的详细信息;一网打尽';Swift中的例外情况?,ios,swift,swift2,Ios,Swift,Swift2,我正在更新代码以使用Swift,我想知道如何打印与“catch all”子句匹配的异常的错误详细信息。为了说明我的观点,我稍微修改了这个例子: do { try vend(itemNamed: "Candy Bar") // Enjoy delicious snack } catch VendingMachineError.InvalidSelection { print("Invalid Selection.") } catch VendingMachineError.
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?
}
如果捕获到意外异常,我需要能够记录导致异常的原因。我刚刚发现了它。我注意到Swift文档中有一行: 如果catch子句未指定模式,则该子句将匹配任何错误并将其绑定到名为error的本地常量 所以,我尝试了这个:
do {
try vend(itemNamed: "Candy Bar")
...
} catch {
print("Error info: \(error)")
}
它给了我一个很好的描述。来自Swift编程语言:
如果catch
子句未指定模式,则该子句将匹配任何错误并将其绑定到名为error
的局部常量
也就是说,catch
子句中有一个隐式的let error
:
do {
// …
} catch {
print("caught: \(error)")
}
或者,似乎let constant\u name
也是一种有效的模式,因此您可以使用它来重命名错误常量(如果名称error
已经在使用,这可能很方便):
do {
// …
} catch let myError {
print("caught: \(myError)")
}