【问题标题】:Functions or methods that throw errors in Swift在 Swift 中抛出错误的函数或方法
【发布时间】:2016-02-19 14:06:46
【问题描述】:

当你在 Swift 中发现第 3 方函数或方法抛出错误时,有没有办法知道它可能抛出什么错误?

该信息在函数或方法签名中不可用。它只是说它抛出了一些东西......

【问题讨论】:

  • 如果API/文档没有告诉你,那你就无法知道。
  • 听起来绝对像一个错误,而不是一个功能。将此作为答案发布,我会接受。

标签: swift cocoa error-handling swift2


【解决方案1】:

错误以标准方式传播。尝试通过向函数传递错误数据或禁用某些硬件(如网络适配器...)来模拟错误并尝试转储它

import Foundation

func foo() throws ->Void {
    // anonymous Error
    struct Error: ErrorType {
        var msg = "error msg"
    }
    throw Error()
}

func boo() throws ->Void {
    // anonymous NSError
    let e = NSError(domain: "domain", code: 100, userInfo: nil)
    throw e
}


do {
    try foo()
} catch let e {
    print("foo throws:", e.dynamicType)
    dump(e)

}
do {
    try boo()
} catch let e {
    print("boo throws:", e.dynamicType)
    dump(e)
}
/* prints

foo throws: (Error #1)
▿ (foo () throws -> ()).(Error #1)
- msg: error msg
boo throws: NSError
▿ Error Domain=domain Code=100 "(null)" #0
- NSObject: Error Domain=domain Code=100 "(null)"

*/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多