How to properly handle errors on iPhone


I have a question about error/exception handling on the iPhone.

I've read the documentation about Exception, and it seems exceptions can be used only for exceptional situations.

Does it mean you can't use them like in java ?

for example, I'm trying to write a use case controller for my application. I've got a few examples in Java from previous projects in that language, that use exceptions in case of errors.

the question put simply is: can I follow the example I've got in Java, and "translate" it in Objective-C (and use Objective-C exceptions) or is there a better way to do that ?

here is the code I would like to make objective-c friendly:

public void addPerformance(Perfomance perf) {
        //do some preparation
    //execute the usecase
        executor(new AddPerformance(perf));

    private void executor(Usecase usecase) {

            try {
            } catch (RealException re) {
                throw re;
            } catch (Exception e) {
                throw new FatalException(this.getClass().getName() + " / executor("
                        + usecase.getClass().getSimpleName() + ")", e,
                        "\n\t |*| : Unexpected exception translated into FatalException");
            } finally {

All the exceptions are meant to be caught by the UI to display an error message.

thanks for your help, Michael

In general, yes, you can translate your try/catch logic into a comparable construct in Objective-C and get comparable results. Though do be careful with that throw re; line, as an uncaught exception on the iPhone will crash your app.

More to the point however, the standard pattern used by the iPhone SDK and other commonly used libraries is that instead of throwing exceptions, API methods that may fail for a variety of reasons return a boolean value indicating whether or not the operation was successful, and accept as a parameter a reference to an NSError pointer that is used in the event of an error to provide the caller with specific details about what went wrong. So in this case, your code might translate to something more like:

NSError* error = nil;
[[UnitOfWorkServices sharedInstance] bizTransactionStart];
bool success = [usecase execute:&error];
if (success) {
    [[UnitOfWorkServices sharedInstance] bizTransactionCommit];
else if (error) {
    int code = [error code];
    [[UnitOfWorkServices sharedInstance] bizTransactionEscape];
    if (code == MY_MINOR_ERROR_CODE) {
        //do something
    else if (code == MY_FATAL_ERROR_CODE) {
        //do something else
    else {
        //handle unexpected error type(s)
else {
    //operation failed with no specific error details
    [[UnitOfWorkServices sharedInstance] bizTransactionEscape];
    //handle generic error
[[UnitOfWorkServices sharedInstance] bizTransactionEnd];