swift - 为什么 Swift 在我的错误处理中看不到 "deeply"?

标签 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 {
        //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/

相关文章:

swift - insertRowsAtIndexPaths 跳转自定义单元格 UITableView 和 UITableViewAutomaticDimension

swift - 无法在 Ubuntu 14.04 上使用 Swift 编译 "hello world"程序

ios - 访问扩展文件中一个文件中声明的变量时出现问题

ios - 单元格 ImageView 缩进

swift - 初始化 GMSMapView 崩溃

ios - 如何将音频文件从我的网站合并到我的 iOS 应用程序?

objective-c - Swift 函数未包含在自动生成的 -Swift.h 伞文件中

ios - 如何防止 UITabBarItem 标题被 Controller 标题覆盖?

ios - 为什么登录时未调用 "ASAuthorizationControllerDelegate"?

swift - 自定义类 swift 设置约束到 superview