0

How should I properly handle errors in an initialiser which performs various configurations of the object during creation?

Would it be a bad to throw an exception? What about returning NSError?

Pétur Ingi Egilsson
  • 4,368
  • 5
  • 44
  • 72

1 Answers1

1

Well seeing how your init method returns type id or more recently, instancetype, you cannot return an NSError *. Exceptions seem like the way to go for your situation. With these, you have two choices.

Choice 1 Throwing Exceptions. In this case, if you see something going wrong, just throw an exception.

- (id)init {
    ...
    ...
    if (shouldThrowException) 
        NSException *myException = [NSException new]
        ... populate this exception with details ...
        @throw(myException)
}

Choice 2 Catching Exceptions. In this case, if you do not care what goes wrong, you can just ignore any exceptions raised.

- (id)init {
    ...
    ...
    @try {
        // some dangerous thing
    } @catch (NSException *e) {}
}
Brian Tracy
  • 6,801
  • 2
  • 33
  • 48