Correct Structure to check for Errors using NSError

前端 未结 4 1880
囚心锁ツ
囚心锁ツ 2021-02-02 01:59

I\'m coding up various routines and I\'m trying my best to keep it neat and refactored.

Methods I\'m creating are starting to look similar to this code:

         


        
4条回答
  •  名媛妹妹
    2021-02-02 02:32

    Note: When I posted this I was unaware of any MacOS/Cocoa exceptions debate. Please bear this in mind when you consider this answer.

    Why not use exceptions instead? This will allow you to dispense with the error parameter on your methods and handle your errors in one place.

    -(IBAction)buttonPress:(id)sender {
        // Create Document Shopping List with this document
        @try {
            [self doSomething];
            [self doSomethingElse];
            [self doYetSomethingElse];
        } @catch (NSException* e) {
            [NSApp presentException:e];
        }
        return nil;
    }
    

    You will of course need to throw exceptions as required from within your doXXXX methods:

    NSException* e = [NSException exceptionWithName:@"MyException"
                                             reason:@"Something bad happened"
                                           userInfo:nil];
    @throw e;
    

提交回复
热议问题