How to handle initialization failures?


#1

At the moment I am writing my first little program and I asked myself how to handle initialization failures correctly.

[code]- (id)initWithFileURL:(NSURL *)fURL withContent:(SMFileContentType)fileType
{
self = [super init];

if (self) {
 
    // Check if the file exists
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[fURL path]];
    
    // Does the file exist?
    if (fileExists) {
      // do something
    } else {
        // Initialization failed because I need some file attributes to initialize
        self = nil;
        return self;
    }
}
return self;

}
[/code]
I am not sure, if the above code is OK (ARC is enabled) - I think it wouldn’t be a good idea to throw an exception here, but maybe I am wrong.
All tips and hints are welcome.

cu
Vertex


#2

That -init method looks fine. Returning nil is the right thing to do in this case. In Objective-C, exceptions are usually used to report programmer errors.


#3

Thanks Adam for the quick response, now I feel more confident.

Have a nice sunday!
Vertex