Swift 中的 Catch 子句必须是详尽无遗的。这是否意味着每当我想避免错误传播时,我总是需要使用通配符或空 catch 子句?示例:
enum Oops: Error {
case oh, ouch, meh
}
func troublemaker() {
do { throw Oops.meh }
catch Oops.oh {}
catch Oops.ouch {}
catch Oops.meh {}
// Error: Error is not handled because the enclosing catch is not exhaustive
}
当然,如果我在函数中添加throws
就解决了。添加 catch {}
或 catch _ {}
也是如此。
但是有什么办法可以用其他方式制作详尽的 catch block 吗?比如,也许定义了允许抛出的错误类型,这样我的枚举 Error 就会使其变得详尽无遗?
最佳答案
如果你只是不喜欢多个 catch block ,一次捕获所有错误然后切换错误类型
func troublemaker() {
do { throw Oops.meh }
catch let error{
switch error {
case Oops.meh:
print("It works!")
break
default:
print("Oops something else is wrong")
break
}
}
}
关于swift - Swift 3.1 中没有空或通配符的详尽 catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45104487/