I cannot catch the "No space left on device" exception when using NSFileHandle writedata function
Asked Answered
S

2

12

I used NSFileHandle to writedata to a file.

NSFilehandle *handle = [NSFileHandle fileHandleForWritingAtPath:@"path/of/file"];

@try {
    [handle writedata:data];
} @catch (NSException *e) {
    // when exception occur, never got here 
     NSLog(@"%@", e);
}

As my device disk space is full, calling writedata will fail. But I can't catch the exception.

My program log info:

2014-05-23 16:17:24.435 mytest[12919:3203] An uncaught exception was raised
2014-05-23 16:17:24.435 mytest[12919:3203] *** -[NSConcreteFileHandle writeData:]:
      No space left on device
2014-05-23 16:17:24.436 mytest[12919:3203] (
0 CoreFoundation 0x00007fff8fae725c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff8cbb3e75 objc_exception_throw + 43
2 CoreFoundation 0x00007fff8fae710c +[NSException raise:format:] + 204
3 Foundation 0x00007fff93640f31 __34-[NSConcreteFileHandle writeData:]_block_invoke + 84
4 Foundation 0x00007fff93840020 __49-[_NSDispatchData enumerateByteRangesUsingBlock:]_block_invoke + 32
5 libdispatch.dylib 0x00007fff8bfc2fad _dispatch_client_callout3 + 9
6 libdispatch.dylib 0x00007fff8bfc2f28 _dispatch_data_apply + 113
7 libdispatch.dylib 0x00007fff8bfc9502 dispatch_data_apply + 31
8 Foundation 0x00007fff9383fff9 -[_NSDispatchData enumerateByteRangesUsingBlock:] + 83
9 Foundation 0x00007fff93640ed2 -[NSConcreteFileHandle writeData:] + 150
10 ZiSyncMac 0x000000010000b1eb -[TransferFile writePart:data:] + 475

I found out writedata calls a dispatch to do real write data to the file system. So I think writedata will throw a exception in GCD.

How can I handle the GCD exception in my code?

Suellensuelo answered 23/5, 2014 at 8:56 Comment(0)
N
1

From a website that's been hijacked since (not providing the link for that reason, but the explanation is still useful):

seekToEndOfFile() and writeData() are not marked as throws (they don’t throw an NSError object which can be caught in with a do-try-catch block), which means in the current state of Swift, the NSExceptions raised by them cannot be “caught”.

If you’re working on a Swift project, you could create an Objective-C class which implements your NSFileHandle methods that catches the NSExceptions (like in this question), but otherwise you’re out of luck.

Nonaligned answered 9/2, 2018 at 14:52 Comment(0)
M
0

What @eric said is right. But, what you can do is check before that you write for how much space is left in the disk and only after it write to the disk.

Michelle answered 24/12, 2018 at 9:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.