Swift 3.1中没有空或通配符的详尽捕获块 [英] Exhaustive catch blocks without empty or wildcard in Swift 3.1

查看:69
本文介绍了Swift 3.1中没有空或通配符的详尽捕获块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

catch子句必须是详尽的。这是否意味着我想避免错误传播时,总是需要使用通配符或空catch子句?示例:

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
}

当然,如果我将 throws 添加到函数中,则该问题已得到修复。添加 catch {} catch _ {} 也是一样。

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

但是有其他方法可以使穷举式捕获块吗?例如,也许定义了允许抛出的错误类型,所以我的枚举Error会使它详尽无遗?

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?

推荐答案

不喜欢多个catch块,立即捕获所有错误,然后切换错误类型

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

这篇关于Swift 3.1中没有空或通配符的详尽捕获块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆