NSFileHandle writeData: exception handling

匆匆过客 提交于 2019-12-05 00:40:44

问题


This could be rather broad problem but I could not find any online resource addressing or explaining this matter.

The question is after creating NSFileHandle *writer = [NSFileHandle fileHandleForWritingAtPath:"path"] and when you use [writer writedata:"NSData"] there are sine possible exception that could fire according to the apple doc.

"This method raises an exception if the file descriptor is closed or is not valid, if the receiver represents an unconnected pipe or socket endpoint, if no free space is left on the file system, or if any other writing error occurs." - APPLE DOC

All I want to know is is there any way we can handle or validate these issues without using any try catch or checking for each error in a condition check before write. Any possible way we can use NSError to handle this ?


回答1:


I would say "No". If you did manage to find a test that covered all possible failures before writing, then there is nothing to say that the write operation might fail after this initial test (think about writing to a filesystem with 1KB free and you want to write 4KB).

Therefore wrapping your calls to these methods inside a @try/@catch block would seem to me to be the best approach. These wrappers could then return an NSError ** if you want details of the failure (which you most certainly should want).

- (BOOL)writeData:(NSData *)data
     toFileHandle:(NSFileHandle *)fileHandler
            error:(NSError **)error
{
    @try
    {
        [fileHandler writeData:data];
    }
    @catch (NSException *e)
    {
        if (error != NULL)
        {
            NSDictionary *userInfo = @{ 
                NSLocalizedDescriptionKey : @"Failed to write data",
                // Other stuff?
            };
            *error = [NSError errorWithDomain:@"MyStuff" code:123 userInfo:userInfo];
        }
        return NO;
    }
    return YES;
}

You will certainly want to get the reason for the failure into the NSError, but it's not immediately obvious to me how to go about doing this.



来源:https://stackoverflow.com/questions/16939295/nsfilehandle-writedata-exception-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!