在目标c中抛出自定义异常

时间:2013-10-07 04:29:39

标签: ios objective-c try-catch throw nsexception

我有以下代码。 。 。

@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;

}

请帮忙修复此问题,我想为callStackSymbols添加一些额外的对象。 。 。 。谢谢提前

1 个答案:

答案 0 :(得分:2)

如果您来自Java背景,Objective-C中的异常处理起初会感觉很奇怪。实际上,您通常不会将NSException用于自己的错误处理。使用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字典中,并将此错误传递给调用者,如上所示。

相关问题