Menu
CoddyTech

throws 和 Error

本课属于 Coddy Swift 学习旅程的“逻辑与流程”单元。第 44 课,共 56 课。

Swift 通过要求函数声明它们可能失败来处理错误。函数体会抛出一个错误值,调用方必须处理它。

错误类型是指任何符合内置 Error 协议的类型。声明自定义错误类型最简单的方法是使用枚举:

enum InputError: Error {
    case empty
    case tooLong
}

会抛出错误的函数会在其签名中使用 throws 关键字,并在函数体中使用 throw 语句:

func validate(_ s: String) throws -> String {
    if s.isEmpty { throw InputError.empty }
    if s.count > 100 { throw InputError.tooLong }
    return s
}

你不能直接调用会抛出异常的函数,编译器会强制要求你处理错误。下一课会介绍具体方法。

challenge icon

挑战

简单

定义一个枚举 NumError: Error,包含两个情况:negative 和 tooBig。

定义一个会抛出异常的函数 doubleSafely(_ n: Int) throws -> Int,该函数:

  • 当 n < 0 时抛出 .negative
  • 当 n > 100 时抛出 .tooBig
  • 否则返回 n * 2

从标准输入中读取一个整数。在 do/catch 代码块中调用 doubleSafely(你会在下一课学习确切的写法,现在请使用下面这个固定框架):

do {
    let result = try doubleSafely(n)
    print("ok: \(result)")
} catch NumError.negative {
    print("negative")
} catch NumError.tooBig {
    print("too big")
} catch {
    print("unknown")
}

输入 10 时,输出为 ok: 20。输入 -1 时,输出为 negative。输入 500 时,输出为 too big。

亲手试试

let n = Int(readLine()!)!

// TODO: enum NumError: Error { case negative, tooBig }
// func doubleSafely(_ n: Int) throws -> Int { ... }
// do { let r = try doubleSafely(n); ... } catch NumError.negative { ... } ...
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: Swift 在线编辑器