看到这个错误:
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
涵盖了所有的可能性。为什么 Swift 不“深入”分析所有的可能性并告诉我没有错?
例如,在此处搜索“捕获 VendingMachineError.InvalidSelection”:https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42-ID508
您会在那里看到 Apple 正在按我的方式行事。他们的代码有错吗?
最佳答案
编译器很难准确知道一段代码可能导致哪些异常,因为任何未在更深层次处理的异常都会向上传播。虽然您的情况相对简单,但通常是一个非常困难的问题。
请注意,代码在任何地方都没有说明它可以抛出哪些异常,只是说它可以抛出一些东西......
关键陈述:
For example, the following code handles all three cases of the VendingMachineError enumeration, but all other errors have to be handled by its surrounding scope
因此,在他们的示例中,虽然他们没有显示,但那段代码的容器也必须能够抛出。这是因为它不处理所有可能的异常。
对于您的情况,asdf
需要被定义为 throws
或者它需要一个 catch all。
关于swift - 为什么 Swift 在我的错误处理中看不到 "deeply"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33465087/