Question

I'm looking to start putting error catches into my code, and I want to see what NSError objects do for me on their own and what I'd have to add in myself.

Looking at this SO question and the Apple Docs, it looks like all NSError does is hold onto a numeric error code, the location of the error, and a description of the error. For all three of these items, I have to specify them in my code. Then, if I want to do something like skip to the end of any methods currently being executed (that would most likely cause a crash if the app tried to run them), or display a UIAlertView telling the user there was an error, I have to specify all of that on my own as well, correct?

I'm a bit of a beginner, so is there anything else I would want to consider doing?

Was it helpful?

Solution

NSError is a container for error information, it does not do anything on its own. The class is designed so that different parts of your code could communicate error information to each other in a standardized way. Simply setting an error inside a method that takes NSError** does nothing - it's the responsibility of the caller to check if *error is non-nil, skip to the end of the method, display localized description, prompt the user for an action, and so on.

However, NSError is flexible enough to enable you to do all that: the caller can provide pretty much any kind of information; you can track recovery attempts, display localized messages to the user, or store additional information in the NSError object, and return it further down the call chain.

Note: Cocoa framework methods generally require that you check the direct return value before using the NSError, not checking whether the error is nil. The error is guaranteed to be valid if the method indicates failure, but it is not guaranteed to be nil for success, even if you set it to nil beforehand.

OTHER TIPS

NSError is provided as an encapsulation of errors. It is a good OO practice and it allows for other signatures to strongly type against it. This is much like the Exception class in Java and C#. It also allows you to create a pointer to pass into a method that takes NSError as an argument, after the method finishes, you can check NSError for conditions your application can handle.

You might want to look into posting some code to help illustrate what you are trying to accomplish.

One thing you could do is, after calling the method that would populate an error object, check if the error is not nil, or evaluate the properties of the error object.

It could look something like:

-(void)someMethod {
    NSError *error;

    [self myMethod:&error];

    if ( error ) {
        // handle the error, display an alert, etc ...
    }
    else {
        // do other stuff when no error occurs
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top