ios 如何在 Swift 中打印“捕获所有”异常的详细信息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31352593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print details of a 'catch all' exception in Swift?
提问by markdb314
I'm updating my code to use Swift, and I'm wondering how to print error details for an exception that matches the 'catch all' clause. I've slightly modified the example from this Swift Language Guide Pageto illustrate my point:
我正在更新我的代码以使用 Swift,我想知道如何打印与“全部捕获”子句匹配的异常的错误详细信息。我稍微修改了这个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?
}
If I catch an unexpected exception, I need to be able to log something about what caused it.
如果我捕捉到意外异常,我需要能够记录导致异常的原因。
回答by markdb314
I just figured it out. I noticed this line in the Swift Documentation:
我只是想通了。我在 Swift 文档中注意到了这一行:
If a catch clause does not specify a pattern, the clause will match and bind any error to a local constant named error
如果 catch 子句未指定模式,则该子句将匹配任何错误并将其绑定到名为 error 的本地常量
So, then I tried this:
所以,然后我尝试了这个:
do {
try vend(itemNamed: "Candy Bar")
...
} catch {
print("Error info: \(error)")
}
And it gave me a nice description.
它给了我一个很好的描述。
回答by Arkku
From The Swift Programming Language:
来自Swift 编程语言:
If a
catch
clause does not specify a pattern, the clause will match and bind any error to a local constant namederror
.
如果
catch
子句未指定模式,则该子句将匹配任何错误并将其绑定到名为 的本地常量error
。
That is, there is an implicit let error
in the catch
clause:
也就是说,子句中有一个隐含let error
的catch
:
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):
或者,这似乎let constant_name
也是一个有效的模式,因此您可以使用它来重命名错误常量(如果名称error
已被使用,这可能会很方便):
do {
// …
} catch let myError {
print("caught: \(myError)")
}