函数在Swift中抛出了哪些错误?

时间:2017-04-07 05:23:33

标签: ios swift error-handling throws

我看到一些方法会在Apple的文档中抛出错误。但我无法找到有关它抛出的信息。

喜欢以下方法。它在FileManager类中。

func moveItem(at srcURL: URL, to dstURL: URL) throws

我想知道它会抛出什么样的错误。我在哪里可以获得相关信息?

1 个答案:

答案 0 :(得分:0)

与Java不同,throws声明需要一个类型,在Swift中你不会知道将抛出什么类型的Error。您唯一知道的是该对象符合Error - 协议。

如果您知道某个函数抛出了一个certein Error(因为它有详细记录),您将需要正确地转换捕获的对象。

示例:

do {
    try moveItem(from: someUrl, to: otherUrl)
} catch {
    //there will automatically be a local variable called "error" in this block
    // let's assume, the function throws a MoveItemError (such information should be in the documentation)
    if error is MoveItemError {
        let moveError = error as! MoveItemError //since you've already checked that error is an MoveItemError, you can force-cast
    } else {
        //some other error. Without casting it, you can only use the properties and functions declared in the "Error"-protocol
    }
}