在Swift中抛出错误的函数或方法

时间:2015-11-18 00:45:59

标签: swift cocoa error-handling swift2

当您在Swift中发现抛出错误的第三方函数或方法时,是否有任何方法可以知道它可能会抛出哪些错误?

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

1 个答案:

答案 0 :(得分:0)

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

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)"

*/
相关问题