Catch NSFileHandleOperationException in Swift

How can I catch an NSFileHandleOperationException in Swift?

I use fileHandle.readDataToEndOfFile() , which raises (according to the documentation) fileHandle.readDataOfLength() , which can throw (again according to the documentation) NSFileHandleOperationException .

How can I catch this exception? I tried

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

but xcode says

A warning. There are no calls to function in the try expression

Warning: the catch block is not available because no errors are generated in the do block

How can I do it? 😄

Edit: I decided to use C kind old fopen , fread , fclose as a workaround:

 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$ (an abbreviation for the KizzyCode standard library) is a prefix because extensions are modular. The above code is placed in the Public Domain 😊

I will leave it open, because it is, nevertheless, an interesting question.

+5
source share

All Articles