Exceptions are very rarely used for a control flow such as this in Objective-C. I assume you have a Java (or similar) background.
Iβm not saying that you cannot write such code, but it will be very strange for other people who are looking at your code, and can also work poorly if they are used by other people's code, if you are not completely isolated except that he never reaches his code.
As is usually done in Objective-C
Exceptions are used for critical errors. If the expected error (as if it seems like you want @try
), you should try and return an NSError
. This is a design pattern that is used in all Foundation and Cocoa frames, as well as third-party frameworks. See an example on the net reading / writing files or JSON code ( JSONObjectWithData:options:error:
what would you do
What you do is add an error parameter (double pointer) at the end of your method, which may fail, for example:
- (MyResultObject *)myMethodThatCouldFailWith:(MyObject *)myObject error:(NSError **)error;
When someone (you or someone else) uses this method, they can, if they want to pass an NSError pointer, which will be set if an error occurs, for example:
NSError *error = nil;
Note the ampersand ( &
) before the error parameter. This means that you send your error points as an argument so that inside the risky method this pointer can be changed to points on a new NSError
object, which can be read after the method returns.
Now, inside your method that might fail, you should set an error for the new NSError
object if something went wrong (instead of throwing an exception). Nil is also returned very often when an error occurs, as this probably means that the calculation will fail or that the data is unreliable or irrelevant.
- (MyResultObject *)myMethodThatCouldFailWith:(MyObject *)myObject error:(NSError **)error { // Do something "risky" ... MyResultObject *result = [MyResultObject somethingRiskyWith:myObject]; // Determine if things went wrong if (!result) { // Set error if a pointer for the error was given if (error != NULL) { *error = [NSError errorWithDomain:yourErrorDomain code:yourErrorCode userInfo:optionalDictionaryOfExtraInfo]; } return nil; } // Everything went fine. return result; }
Now, if the error is correct, you can determine which error was from the error code you specified, and you can read more detailed information in the user information dictionary (where you can add a lot of information).