2015-12-08 49 views
0
do { 
    try thingOne() 
    try thingTwo() 
    try manager.removeItemAtPath("myPath") //NSFileManager instance 
} catch ThingOneErrorType.SomeError { 
    //code here 
} catch { 
    //Need to respond explicitly to manager.removeItemAtPath but how? 
} 

我使用一個包含多個try語句一個do塊中的NSFileManager removeItemAtPath實例方法,我想明確地捕捉錯誤來自fileManager。我的問題是,如果我查看docs for NSFileManager,我無法確定哪些ErrorTypes removeItemAtPath可能會丟失。如何抓具體try語句的DO塊多try語句雨燕2.0

我意識到我可以通過嵌套塊來解決這個問題,但那會很快成爲嵌套混亂。

那麼,我該如何確定在具有多個try語句的do塊中的特定try語句中拋出什麼錯誤?

回答

1
do { 
    try thingOne() 
    try thingTwo() 
    try manager.removeItemAtPath("myPath") //NSFileManager instance 
} catch ThingOneErrorType.SomeError { 
    //code here 
} catch let error as NSError { 
    //Need to respond explicitly to manager.removeItemAtPath but how? 
    print("Error: \(error.domain)") 
} 

可能

} catch NSCocoaError.FileNoSuchFileError { 
    print("Error: no such file exists") 
} 

會在你的情況作品...(我沒有檢查!)。 error.domain將幫助您識別它

您可以識別哪個語句通過使用'extra'語句拋出錯誤,或者在拋出函數成功返回的幫助下更好。我們可以對這種方法說些什麼?你最好重新設計你的代碼。錯誤處理應該用作錯誤處理,而不是作爲程序流程的一部分。

import Foundation 
struct E: ErrorType{} 
func foo() throws -> Void { 
    let r = random() % 3 
    if r == 0 { 
     throw E() 
    } 
} 
var fail = 0 
do { 
    try foo() 
    fail++ 
    try foo() 
    fail++ 
    try foo() 
    fail++ 
} catch let e as E { 
    print("failed in :",fail, "attempt") 
} 

//失敗:14:嘗試

+0

如果我有多個try語句每一個可能引發同一類型的錯誤或有具有大量可能出現的錯誤,可能被拋出方法?然後我需要嵌套我的陳述? – nwales

+0

如果您的多個語句可能拋出相同的錯誤,您是否確實需要在您的代碼中執行另一個操作?嗯...在這種情況下,你必須使用分離的do/try/catch塊... – user3441734