【问题标题】:Swift 2.1 - Error Handling - Multiple Catch is not compiledSwift 2.1 - 错误处理 - 未编译多个 Catch
【发布时间】:2016-01-06 13:06:39
【问题描述】:

我有一个函数 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")
    }     
}

提前致谢!

【问题讨论】:

标签: ios xcode swift2


【解决方案1】:

您需要包含一个默认的 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 块后,您在下面的 cmets 中提到该函数 catchingSpecificError() 不会投射您期望的错误;或者更确切地说,默认的 catch 块会捕获您的错误。

现在,由于我不知道您的代码的上下文,因此我无法推断您的情况实际上出了什么问题。我将在下面为您发布一个工作示例——在这个问题的上下文中——投掷和接球按预期工作。但是请注意,您对guard 块的使用有些不合常规。通常你使用guard就像if let块一样,即guard let name = name else { ..,如果name包含nil,它将进入guard块。

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

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" */

正如预期的那样,我们捕获了函数assignName 抛出的PersonError.IsNotAPerson。希望您可以利用此示例获得自己的代码(您在问题中未向我们展示的部分)。

【讨论】:

  • 谢谢,我尝试使用默认捕获。在我的情况下,抛出方法 assignName(nil) 会抛出 PersonError.IsNotAPerson 错误,但是执行的是默认的 catch,而不是我特别应该捕获 PersonError.IsNotAPerson 错误的 catch。
  • @ShanmugarajaG 乐于助人。我为您添加了一个示例,希望您可以将其与您自己的实现(您尚未向我们展示)进行比较,并了解您的案例为什么不能按预期工作。如果您仍然得到意想不到的结果,可能会在您的问题中添加更多详细信息。
  • 谢谢,它起作用了,我没有将 nil 传递给 assignName(),而是传递了一个 String 类型的参数?并且价值为零。它奏效了。
猜你喜欢
  • 1970-01-01
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多