gpt4 book ai didi

swift - 在 Swift 中捕获 NSFileHandleOperationException

转载 作者:行者123 更新时间:2023-12-04 12:53:16 26 4
gpt4 key购买 nike

我怎样才能 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/

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