iphoneobjective-ciosnsexception

iphone - try, catch question


I have a method that has several parts that can throw an exception. If one of these parts fail, I would like the cleaning method to run. I am thinking about using the try/catch directive.

My question is: will I have to use one directive for every line of code that can throw an exception or can I simply include the whole method in a block like this?

 @try {
    [self doStuff];
     // doStuff has several passages that could throw an exception

 }
 @catch (NSException * e) {
    [self cleanTheWholeThing];
 }

In this case it is not important to me which line generated the problem. I just need the method to run successfully or do other stuff in case it fails.

thanks


Solution

  • You can certainly have multiple lines in your try block. Example:

    @try {
        if (managedObjectContext == nil) {
            actionMessage = @"accessing user recipe library";
            [self initCoreDataStack];
        }
        actionMessage = @"finding recipes";
        recipes = [self recipesMatchingSearchParameters];
        actionMessage = @"generating recipe summaries";
        summaries = [self summariesFromRecipes:recipes];
    }
    @catch (NSException *exception) {
        NSMutableDictionary *errorDict = [NSMutableDictionary dictionary];
        [errorDict setObject:[NSString stringWithFormat:@"Error %@: %@", actionMessage, [exception reason]] forKey:OSAScriptErrorMessage];
        [errorDict setObject:[NSNumber numberWithInt:errOSAGeneralError] forKey:OSAScriptErrorNumber];
        *errorInfo = errorDict;
        return input;
    } @catch (OtherException * e) {
        ....
    } @finally {
        // Any clean up can happen here.  
        // Finally will be called if an exception is thrown or not.
    }
    

    And a link to practical use of exceptions:

    https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Exceptions/Tasks/HandlingExceptions.html