为什么';t Swift look“;“深深地”;在我的错误处理?
请参阅此错误:为什么';t Swift look“;“深深地”;在我的错误处理?,swift,Swift,请参阅此错误: enum MyError: ErrorType { case Foo case Bar } func couldThrow(string: String) throws { if string == "foo" { throw MyError.Foo } else if string == "bar" { throw MyError.Bar } } func asdf() { do {
enum MyError: ErrorType {
case Foo
case Bar
}
func couldThrow(string: String) throws {
if string == "foo" {
throw MyError.Foo
} else if string == "bar" {
throw MyError.Bar
}
}
func asdf() {
do {
//Error: Errors thrown from here are not handled
//because the enclosing catch is not exhaustive.
try couldThrow("foo")
} catch MyError.Foo {
print("foo")
} catch MyError.Bar {
print("bar")
}
}
然而,我的catch
es涵盖了所有的可能性。为什么斯威夫特不“深入”分析所有的可能性,告诉我一切都没有错
例如,在此处搜索“catch VendingMachineError.InvalidSelection”:
在那里你会看到苹果是按照我的方式做的。他们的代码错了吗?编译器很难确切地知道一段代码可能导致哪些异常,因为没有在更深层次上处理的任何异常都会向上传播。虽然你的情况相对简单,但这通常是一个非常困难的问题 请注意,代码没有说明它可以抛出哪些异常,只说明它可以抛出某些异常 关键声明: 例如,以下代码处理VendingMachineeError枚举的所有三种情况,但所有其他错误都必须由其周围的范围处理 因此,在他们的示例中,虽然没有显示,但该代码段的容器也必须能够抛出。这是因为它不能处理所有可能的异常
对于您的情况,
asdf
需要定义抛出
,或者它需要一个总括。虽然Wain的答案是正确的,但有另一种方法可以消除错误:使用试试
将任何未处理的错误视为致命的运行时错误
func asdf() {
try! {
do {
//Error: Errors thrown from here are not handled
//because the enclosing catch is not exhaustive.
try couldThrow("foo")
} catch MyError.Foo {
print("foo")
} catch MyError.Bar {
print("bar")
}
}()
}