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?
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?
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) {}
}