用 throws、try 和 catch 处理错误

版本新特性 / Swift 2.0

// *** 以前 ***
// 错误通过 NSError 指针返回,结果是可选的,
// 而且没有任何机制强制调用方去检查二者
var error: NSError?
let text = String(contentsOfFile: "/etc/hosts",
                  encoding: NSUTF8StringEncoding,
                  error: &error)
if text == nil {
    print("failed: \(error!)")
}

// *** 在 2.0 版本中 ***
// 可能失败的调用要标上 try,编译器不允许遗漏:
// 要么捕获错误,要么函数自身 throws
do {
    let text = try String(contentsOfFile: "/etc/hosts",
                          encoding: NSUTF8StringEncoding)
    print(text)
} catch {
    print("failed: \(error)") // error is bound by itself, without a declaration
}

func loadAll() throws -> String {
    return try String(contentsOfFile: "/etc/hosts",
                      encoding: NSUTF8StringEncoding)
}