6

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

4

1 回答 1

2

如果你来自 Java 背景,Objective-C 中的异常处理一开始会感觉很奇怪。事实上,您通常不会将NSException其用于您自己的错误处理。在处理意外错误情况(例如 URL 操作)时,请使用NSError它,因为您可以通过 SDK 在许多其他点找到它。

错误处理(大致)如下完成:

编写一个将指向 NSError 的指针作为参数的方法...

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

userInfo 字典是放置错误需要提供的任何信息的地方。

调用该方法时,您会检查这样的错误情况......

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

如果您正在调用可能导致“ NSError != nil”的 SDK 方法,您可以将您自己的信息添加到 userInfo 字典中,并将此错误传递给调用者,如上所示。

于 2014-01-30T08:28:48.270 回答