Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throwing custom exception in objective c

I have following code . . .

@try
{
    NSArray * array = [[NSArray alloc] initWithObjects:@"1",@"2",nil];

   // the below code will raise an exception

   [array objectAtIndex:11];
}
@catch(NSException *exception)
{
    // now i want to create a custom exception and throw it .

    NSException * myexception = [[NSException alloc] initWithName:exception.name
                                                           reason:exception.reason
                                                         userInfo:exception.userInfo];


   //now i am saving callStacksymbols to a mutable array and adding some objects

    NSMUtableArray * mutableArray = [[NSMUtableArray alloc] 
                                       initWithArray:exception.callStackSymbols];

    [mutableArray addObject:@"object"];

    //but my problem is when i try to assign this mutable array to myexception i am getting following error

    myexception.callStackSymbols = (NSArray *)mutableArray;

    //error : no setter method 'setCallStackSymbols' for assignment to property

    @throw myexception;

}

please help to fix this , i wanted to add some extra objects to callStackSymbols . . . .Thanks in advance

like image 684
Shaik Riyaz Avatar asked Oct 07 '13 04:10

Shaik Riyaz


1 Answers

If you are coming from a Java background, exception handling in Objective-C feels strange at first. In fact you normally don't use NSException for your own error handling. Use NSError instead, as you can find it at many other points through the SDK, when handling unexpected error situations (e.g. URL operations).

Error handling is done (roughly) like this:

Write a method that takes a pointer to NSError as parameter...

- (void)doSomethingThatMayCauseAnError:(NSError*__autoreleasing *)anError
{
    // ...
    // Failure situation
    NSDictionary tUserInfo = @{@"myCustomObject":@"customErrorInfo"};
    NSError* tError = [[NSError alloc] initWithDomain:@"MyDomain" code:123 userInfo:tUserInfo];
    anError = tError;
}

The userInfo dictionary is the place to put whatever information needs to be provided with the error.

When calling the method, you check for an error situation like this...

// ...
NSError* tError = nil;
[self doSomethingThatMayCauseAnError:&tError];
if (tError) {
    // Error occurred!
    NSString* tCustomErrorObject = [tError.userInfo valueForKey:@"myCustomObject"];
    // ...
}

If you are calling an SDK method that could result in an "NSError != nil", you can add your own information to the userInfo dictionary and pass this error to the caller as shown above.

like image 65
Christian Avatar answered Oct 05 '22 12:10

Christian