swift - 什么样的异常可能 String(contentsOf url :URL) throw?

标签 swift

我正处于重构原型(prototype)以使其更加灵活的阶段。这意味着我想添加错误处理。我的应用程序非常依赖 String(contentsOf:url) ,与处理文件的任何操作一样,它很容易出错。然而,所讨论的 init 方法的签名只是简单地写着:

init(contentsOf url: URL) throws

所以我知道它会抛出……但是它具体抛出什么?当我不知道我可能遇到什么错误时,我不确定我是否理解如何处理错误。 documentation也不说什么。我难住了?

最佳答案

init(contentsOf:) 来自 Foundation 的 NSString API — 因此,像所有 Foundation API 一样,它抛出一个 NSError 来描述错误。您可以像捕获任何其他错误一样捕获它:

do {
    let str = String(contentsOf: theLocalURL)
    // ...
} catch {
    // Present `error.localizedDescription` to the user to let them know what went wrong
}

因为错误是一个NSError,你也可以捕获它来检查它的code/userInfo:

do {
    // Same as above
} catch let error as NSError {
    // Inspect what went wrong.
}

至于您可能期望哪些特定代码,请查看 NSError Codes list 中以 NSFile... 开头的错误代码.如果文件不存在,常见代码可能是 NSFileReadNoPermissionErrorNSFileReadNoSuchFileError,等等。

不过,一般来说,您应该向用户显示错误的 localizedDescription 并中止操作或重试。

关于swift - 什么样的异常可能 String(contentsOf url :URL) throw?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44741741/

相关文章:

swift - 对于 supportedInterfaceOrientations(),Int 不能转换为 UIInterfaceOrientationMak

Swift:私有(private)获取和公共(public)设置

ios - 删除 UITableViewCell 时出现 NSException

ios - 无法为 UITextField 链接 IBOutlet

swift 字典 : Can't completely remove entry

ios - Swift 4 - 'substring(to:)' 已弃用 - 替代我的代码

ios - HitTest (_ :options:) for SCNNodes without physicsBody swift

ios - Swift、单例、代表函数的变量

iOS - 运行 Swift 单元测试时找不到 'MyProject-Swift.h' 文件

swift - SpriteKit - 为什么没有检测到 SKNode 的触摸