Swift 2.0 错误处理

标签 swift error-handling swift2

我的代码如下。

enum NutritionalError: ErrorType {
    case NotEnoughNutrients
    case TooMuchNutrients
    case Other
}

如您所见,我有一个 ErrorType 的 NutritionalError,包含三种不同的情况。

我有一个这样运行的错误处理函数。

func needs(fat: Double, carbohydrate: Double, protein: Double) throws {
    let totalPercent = fat + carbohydrate + protein

    guard totalPercent > 1 else {
        throw NutritionalError.TooMuchNutrients
    }

    guard totalPercent < 1 else {
        throw NutritionalError.NotEnoughNutrients
    }
}

func calculateNeeds(calories: Int, fatPercent: Double, carbohydratePercent: Double, proteinPercent: Double) -> (Int, Int, Int) {
    do {
        try needs(fatPercent, carbohydrate: carbohydratePercent, protein: proteinPercent)
    } catch NutritionalError.NotEnoughNutrients {
        print("Not enought nutrients.")
    } catch NutritionalError.TooMuchNutrients {
        print("Too many nutrients.")
    }
}

在线。

            try needs(fatPercent, carbohydrate: carbohydratePercent, protein: proteinPercent)

我得到一个错误。

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

最佳答案

与错误状态一样,您需要添加一个没有约束的最终 catch

关于Swift 2.0 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32259910/

相关文章:

ios - 带有约束的 Swift TextView 不可见

iOS Swift 4 - 如何在 NavigationController 中推送 UISearchController

php - 设置自定义错误处理程序会大大增加脚本执行时间

php - pg_query错误直接进入控制台,而pg_last_error不返回任何内容

ios - swift - "attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update"

macos - swift 错误 "Immutable value only has mutating members"

swift - 保存由 iphone 上用 swift 编写的应用程序生成的文本文件的路径

ios - Xcode 7.1 iOS 9.1 CLLocationManager 不总是工作?

jquery - 如何从Grails中的AJAX错误回调中检索错误消息?

Swift:Array<Float> 和 [Float] 一样吗?