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

Sha*_*yaz 6 objective-c try-catch throw nsexception ios

我有以下代码...

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

}
Run Code Online (Sandbox Code Playgroud)

请帮助解决这个问题,我想为callStackSymbols添加一些额外的对象....提前致谢

Chr*_*ian 3

如果您有 Java 背景,那么 Objective-C 中的异常处理一开始会感觉很奇怪。事实上,您通常不用于NSException自己的错误处理。而是使用它NSError,因为在处理意外错误情况(例如 URL 操作)时,您可以通过 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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