Swift 2.1 - 错误处理 - 不编译多个Catch

时间:2016-01-06 13:06:40

标签: ios xcode swift2

我有一个函数assignName(name :),它会抛出一个错误。当从具有多个catch的do块调用该函数时,它将错误显示为:

Errors thrown from here are not handled because the enclosing catch is not exhaustive 

我的代码是:

enum PersonError: ErrorType {
    case IsNotAPerson
    case IsNotAGoodPerson
    case IsNotAValidPerson
}

func assignName(name: String?) throws {
    guard name != nil else {
        throw PersonError.IsNotAPerson
    }
    personName = name
}
func catchingSpecificError() {
    do {
        try assignName(nil) // Compiler Error displays at this line.

    }catch PersonError.IsNotAPerson {
        print("Propagated error is caught in catch on case .NotAPerson")
    }     
}

提前致谢!

1 个答案:

答案 0 :(得分:5)

您需要包含一个默认的catch块(就像使用switch case一样),以使您的错误处理无穷无尽;如果抛出的错误不是您指定的错误之一。

func catchingSpecificError() {
    do {
        try assignName(nil) // Compiler Error displays at this line.

    }catch PersonError.IsNotAPerson {
        print("Propagated error is caught in catch on case .NotAPerson")
    }catch {
        print("default..")
    }
}

稍微偏离主题,但我认为personName = name是指我们在上面的示例中看不到的类属性personName

添加了默认的catch块,您在下面的评论中提到函数catchingSpecificError()不会引发您期望的错误;或者更确切地说,默认的catch块会捕获您的错误。

现在,由于我不了解您的代码的上下文,我无法推断出您的情况究竟出了什么问题。我将在下面发布一个工作示例 - 在这个问题的背景下 - 抛出和捕获按预期工作。但请注意,您对guard块的使用有点超出惯例。通常,您使用guard就像if let块一样,即guard let name = name else { ..,如果guard包含name,则会nil块。

无论如何,请考虑以下完全有效的例子:

enum PersonError: ErrorType {
    case IsNotAPerson
    case IsNotAGoodPerson
    case IsNotAValidPerson
}

class Person {
    var personName : String? = ""

    func assignName(name: String?) throws {
        guard name != nil else {
            throw PersonError.IsNotAPerson
        }

        personName = name
    }

    func catchingSpecificError() {
        do {
            try assignName(nil)

        }catch PersonError.IsNotAPerson {
            print("Propagated error is caught in catch on case .NotAPerson")
        }catch {
            print("default..")
        }
    }
}

var myPerson = Person()
var myName : String? = nil

myPerson.catchingSpecificError()
/* Prints: "Propagated error is caught in catch on case .NotAPerson" */

正如预期的那样,我们捕获函数PersonError.IsNotAPerson抛出的assignName。希望你可以利用这个例子来获得你自己的代码(你在问题中没有显示我们的部分)。