Throw a common exception at object c

I have the 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 fix this, I wanted to add some additional objects to callStackSymbols.,. thanks in advance

+6
source share
1 answer

If you come from the Java background, exception handling in Objective-C seems strange at first. In fact, you usually do not 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 situations (such as URL operations).

Error handling is performed (approximately) as follows:

Write a method that takes a pointer to an NSError as a 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 dictionary of user information is the place where you need to put any information with an error.

When you call a method, you check for such an error ...

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

If you call the SDK method, which can lead to " NSError != nil ", you can add your own information to the userInfo dictionary and pass this error to the caller, as shown above.

+2
source

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


All Articles