2017-04-07 49 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

相關問題