2017-04-07 66 views
-1

我看到一些方法抛出Apple的文档中的错误。但是我找不到任何关于它抛出的信息。一个func在Swift中抛出什么样的错误?

像下面这种方法。它在FileManager类中。

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

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

+1

你不觉得这是谷歌的一个问题? –

+0

我试过了。但我没有得到答案。也许我还没有弄清楚关键词。 – Matt

回答

0

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

如果你知道一个函数抛出一个证书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 
    } 
} 
+0

是的,这些信息对我很有用。有什么方法可以知道它符合什么协议?我想知道失败时发生了什么。 – Matt

+0

这是否意味着我应该**从'catch'块获取**信息,而不是**在catch块中做某些事情? – Matt

+0

在你的'catch'-block中,会有一个名为'error'的局部变量。这符合协议'错误'。如果某个方法的文档指出某个对象(我们假设它被称为'CustomError'),则必须使用'as?'将'error'转换为该对象,并且/或者检查'error'类型'如果错误是CustomError {//处理CustomError}' – FelixSFD

相关问题