swift - 在 Swift 中捕获 NSFileHandleOperationException

标签 swift exception

我怎样才能 catch NSFileHandleOperationException在 swift ?
我用 fileHandle.readDataToEndOfFile()调用(根据文档)fileHandle.readDataOfLength()可以抛出(再次根据文档)一个 NSFileHandleOperationException .
我怎样才能捕捉到这个异常?我试过

do {
    return try fH.readDataToEndOfFile()
} catch NSFileHandleOperationException {
    return nil
}
但 Xcode 说

Warning: No calls to throwing functions occur within 'try' expression

Warning: 'catch' block is unreachable because no errors are thrown in 'do' block


我该怎么做呢? 😄
编辑:
我刚刚决定使用 C 的好老 fopen , fread , fclose作为一种解决方法:
extension NSMutableData {
    public enum KCStd$createFromFile$err: ErrorType {
        case Opening, Reading, Length
    }
    
    public static func KCStd$createFromFile(path: String, offset: Int = 0, length: Int = 0) throws -> NSMutableData {
        let fh = fopen(NSString(string: path).UTF8String, NSString(string: "r").UTF8String)
        if fh == nil { throw KCStd$createFromFile$err.Opening }
        defer { fclose(fh) }
    
        fseek(fh, 0, SEEK_END)
        let size = ftell(fh)
        fseek(fh, offset, SEEK_SET)
    
        let toRead: Int
        if length <= 0 {
            toRead = size - offset
        } else if offset + length > size {
            throw KCStd$createFromFile$err.Length
        } else {
            toRead = length
        }
    
        let buffer = UnsafeMutablePointer<UInt8>.alloc(toRead)
        defer {
            memset_s(buffer, toRead, 0x00, toRead)
            buffer.destroy(toRead)
            buffer.dealloc(toRead)
        }
        let read = fread(buffer, 1, toRead, fh)
        if read == toRead {
            return NSMutableData(bytes: buffer, length: toRead)
        } else {
            throw KCStd$createFromFile$err.Reading
        }
    }
}
KCStd$ (KizzyCode 标准库的缩写)是前缀,因为扩展是模块范围的。以上代码特此放在公共(public)领域😊
我将保持开放状态,因为它仍然是一个有趣的问题。

最佳答案

答案似乎是你不能。如果您查看 FileHandle 中的声明,您将看到注释:

/* The API below may throw exceptions and will be deprecated in a future version of the OS.
 Use their replacements instead. */

关于swift - 在 Swift 中捕获 NSFileHandleOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32124486/

相关文章:

c++ - 错误显然是由尚未执行的代码引起的

Java-如何在Junit中使用注解-eclipse

ios - 在哪里设置 UITableViewCell 的可访问性特征?

swift - 准备(对于 : sender:) not getting called during segue from button to tab bar controller (in Swift 4, Xcode 9)

ios - Swift 等效于 Objective-C block ?

swift - 在 Swift 中使用不带逗号、换行符和括号的可变参数打印字符串

ios - NSXMLParser:非 ASCII 字符的意外结果

java - 测试表的最大值时出错?

java - 身份验证失败异常 - 在批量邮件发送代码中

java - 设计 : How to handle illegal console inputs with Scanner?