Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 675
Yifan Wang Avatar asked May 23 '14 08:05

Yifan Wang


1 Answers

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.

like image 168
Eric Avatar answered Nov 04 '22 22:11

Eric