【问题标题】:throwing custom exception in objective c在目标 c 中抛出自定义异常
【发布时间】:2013-10-13 13:39:12
【问题描述】:

我有以下代码。 . .

@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 中添加一些额外的对象。 . . .提前致谢

【问题讨论】:

  • 不要尝试从异常中恢复。 iOS 和 OS X 中的异常应被视为不可恢复的致命程序员错误。

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


【解决方案1】:

如果您来自 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;
}

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

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

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

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

【讨论】:

  • NSError 不是异常抛出。我觉得在java中表述不够清楚
猜你喜欢
  • 1970-01-01
  • 2011-10-06
  • 2012-10-28
  • 2011-05-30
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 2011-04-14
相关资源
最近更新 更多