在Swift中捕获NSFileHandleOperationException

K. *_*ann 7 exception swift

我怎样才能NSFileHandleOperationException在Swift中找到一个?

我使用fileHandle.readDataToEndOfFile()哪些调用(根据文档)fileHandle.readDataOfLength()可以抛出(再次根据文档)a NSFileHandleOperationException.

我怎么能抓住这个例外?我试过了

do {
    return try fH.readDataToEndOfFile()
} catch NSFileHandleOperationException {
    return nil
}
Run Code Online (Sandbox Code Playgroud)

但Xcode说

警告:'try'表达式中不会调用抛出函数

警告:'catch'块无法访问,因为'do'块中没有抛出错误

我该怎么做呢?

编辑:我决定用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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

KCStd$(KizzyCode标准库的缩写)是前缀,因为扩展是模块范围的.以上代码特此放在公共领域

我会保持开放,因为它仍然是一个有趣的问题.

esc*_*ord 1

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

/* The API below may throw exceptions and will be deprecated in a future version of the OS.
 Use their replacements instead. */
Run Code Online (Sandbox Code Playgroud)