gpt4 book ai didi

ios - 如何找到方法可能抛出的错误类型并在 Swift 中捕获它们

转载 作者:IT王子 更新时间:2023-10-29 05:17:19 24 4
gpt4 key购买 nike

<分区>

我正在使用 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 不存在,但我不知道如何捕获此错误。而且我不知道可能会发生什么其他可能的错误。

文档示例

Error Handling documentation有这样的例子

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.")
}

但我不知道如何做类似的事情来捕获具有使用 throws 关键字的方法的标准 Swift 类型的错误。

NSFileManager class reference for contentsOfDirectoryAtPath没有说可能会返回什么样的错误。所以我不知道要捕获什么错误或如果我得到它们如何处理它们。

更新

我想做这样的事情:

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.")
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com