Exhaustive catch blocks without empty or wildcard in Swift 3.1

限于喜欢 提交于 2020-01-15 11:54:10

问题


Catch clauses in Swift must be exhaustive. Does it mean I always need to use a wildcard or empty catch clauses whenever I want to avoid error propagation? Example:

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
}

Of course, it is fixed if I add throws to the function. Same goes for adding either catch {} or catch _ {}.

But is there any way to make exhaustive catch blocks other way? Like, perhaps defining the allowed type of the error to throw, so my enum Error would make it exhaustive?


回答1:


If you simply don't like the multiple catch blocks, catch all errors at once and then switch error types

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
        }
    }
}


来源:https://stackoverflow.com/questions/45104487/exhaustive-catch-blocks-without-empty-or-wildcard-in-swift-3-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!