Running cleanup code?

Generally speaking, goto is bad (we all know why). What would be the best way to implement simple error cleaning (as in the example below) without duplicating code. In my opinion, the code below is fine, I was just wondering what others would do:

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]
    int returnCode = 0;

    // ... Other code

    // WRITE: To file
    if([dataStore writeToFile:savePathData atomically:YES] == NO) {
        NSLog(@"writeToFile ... Error");
        returnCode = 1;
        goto cleanUpCode;
    }

    // ... Other code

    // Clean up
    cleanUpCode:
    [archiver release];
    [newPlanet release];
    [pool drain];
    return(returnCode);
}

EDIT_001:

In general terms, I agree that @try, @catch, @finally is more than certainly the way to go, but I have two small problems.

(1) The three blocks @try, @catch, @finally should be together; you do not have the flexibility to put code between @catch and @finally, which you can bypass.

(2) The Apple documentation for Obj-C 2.0 reads as follows: "Important: Exceptions are resource intensive in Objective-C. You should not use exceptions for general flow control or simply to indicate errors (for example, a file is not available).

much appcreciated

Gary

+3
4

C, , - /.

Goto ; . , . , , .

+5

, , , , ?

, , [pool drain] . , , @try/@finally, return 1 returnCode = 1.

. ( , , ) - - :

 - (void)doSomething {
    NSMutableArray *anArray = nil;
    array = [[NSMutableArray alloc] initWithCapacity:0];
    @try {
       [self doSomethingElse:anArray];
    }
    @finally {
       [anArray release];
    }
}

.

+4

. :

  • , , . RunApplication. "else".

  • try/catch, "catch", .

 e.g. try {
  .. check for error (any function/procedure that checks for an error can throw an exception
 .. do normal processing (still a good idea to factor this out into a procedure, for clarity
 }
 catch  {
     .. handle errors
 }
 finally
 {
     .. do cleanup
 }

, , goto, , , , try/catch .

try/catch .

0

- , . , , , , ( ). , , , , , . .

#define THROW( _name ) goto label_ ## _name
#define CATCH( _name ) label_ ## _name:

    :
    :

    if([dataStore writeToFile:savePathData atomically:YES] == NO) {
        NSLog(@"writeToFile ... Error");
        returnCode = 1;
        THROW( cleanUpCode );
    }

    :
    :

    CATCH( cleanUpCode )

    [archiver release];
    [newPlanet release];
    [pool drain];
-1
source

Source: https://habr.com/ru/post/1727978/


All Articles