如何在 Swift 中打印“捕捉所有”异常的详细信息?

我正在更新代码以使用 Swift,我想知道如何打印与“ catch all”子句匹配的异常的错误详细信息。为了说明我的观点,我稍微修改了这个 快速语言指南页的例子:

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?
}

如果我发现了一个意想不到的异常,我需要能够记录一些关于引起异常的原因。

37368 次浏览

I just figured it out. I noticed this line in the Swift Documentation:

If a catch clause does not specify a pattern, the clause will match and bind any error to a local constant named error

So, then I tried this:

do {
try vend(itemNamed: "Candy Bar")
...
} catch {
print("Error info: \(error)")
}

And it gave me a nice description.

From The Swift Programming Language:

If a catch clause does not specify a pattern, the clause will match and bind any error to a local constant named error.

That is, there is an implicit let error in the catch clause:

do {
// …
} catch {
print("caught: \(error)")
}

Alternatively, it seems that let constant_name is also a valid pattern, so you could use it to rename the error constant (this might conceivably be handy if the name error is already in use):

do {
// …
} catch let myError {
print("caught: \(myError)")
}