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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With