如何find一种方法可能抛出并在Swift中捕获它们的错误

我正在使用NSFileManager.contentsOfDirectoryAtPath获取目录中的文件名数组。 我想使用新的do-try-catch语法来处理错误:

 do { let docsArray = try fileManager.contentsOfDirectoryAtPath(docsPath) } catch { // handle errors print(error) // this is the best I can currently do } 

docsPath一个错误可能是docsPath不存在,但我不知道如何捕捉这个错误。 而且我不知道可能发生的其他可能的错误。

文档示例

error handling文档有这样一个例子

 enum VendingMachineError: ErrorType { case InvalidSelection case InsufficientFunds(centsNeeded: Int) case OutOfStock } 

 do { try vend(itemNamed: "Candy Bar") // Enjoy delicious snack } catch VendingMachineError.InvalidSelection { print("Invalid Selection.") } catch VendingMachineError.OutOfStock { print("Out of Stock.") } catch VendingMachineError.InsufficientFunds(let amountNeeded) { print("Insufficient funds. Please insert an additional \(amountNeeded) cents.") } 

但我不知道如何做类似的捕捉标准的Swifttypes的方法使用throws关键字的错误。

contentsOfDirectoryAtPath的NSFileManager类引用没有说明可能返回哪种types的错误。 所以我不知道要抓住什么错误或如何处理它们。

更新

我想要做这样的事情:

 do { let docsArray = try fileManager.contentsOfDirectoryAtPath(docsPath) } catch FileManagerError.PathNotFound { print("The path you selected does not exist.") } catch FileManagerError.PermissionDenied { print("You do not have permission to access this directory.") } catch ErrorType { print("An error occured.") } 

NSError自动桥接到ErrorType地方成为types(例如NSCocoaErrorDomain成为NSCocoaError )和错误代码成为值( NSFileReadNoSuchFileError成为.FileReadNoSuchFileError

 import Foundation let docsPath = "/file/not/found" let fileManager = NSFileManager() do { let docsArray = try fileManager.contentsOfDirectoryAtPath(docsPath) } catch NSCocoaError.FileReadNoSuchFileError { print("No such file") } catch { // other errors print(error) } 

至于知道哪个错误可以通过特定的调用返回,只有文档可以帮助。 几乎所有的基础错误都是NSCocoaError域的一部分,可以在FoundationErrors.hfind(虽然有一些罕见的错误,在NSPOSIXErrorDomain下Foundation也可能返回POSIX错误),但是这些错误可能并没有被完全桥接,所以你将不得不在NSError级别pipe理它们。

更多的信息可以在«使用Swift和Cocoa和Objective-C(Swift 2.2)中find»

它会返回NSError:

 let fileManager = NSFileManager() do { let docsArray = try fileManager.contentsOfDirectoryAtPath("/") } catch let error as NSError { // handle errors print(error.localizedDescription) // The file “Macintosh HD” couldn't be opened because you don't have permission to view it. } 

你在“更新”部分所要求的是不可能的。 这是抛出函数的决定,让你知道它可能抛出什么,或不显示它,然后你需要处理一个通用的错误。

很多函数都会显示关于抛出错误的信息,例如:

 func startVPNTunnel() throws Description Start the process of connecting the VPN true if the process of connecting the VPN started successfully, false if an error occurred. Parameters error A pointer to a pointer to an NSError object. If specified and the VPN connection process cannot be started due to an error, this parameter will be set to point to an NSError object containing details about the error. See NEVPNManager Class Reference for a list of possible errors. 

编辑:一个可能的原因 – 这样,抛出函数可以改变它所抛出的错误,所有捕获这些错误的代码仍然是有效的。