gpt4 book ai didi

ios - 在 objective-c 中抛出自定义异常

转载 作者:可可西里 更新时间:2023-11-01 03:58:17 25 4
gpt4 key购买 nike

我有以下代码。 . .

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

最佳答案

如果您有 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 字典并将此错误传递给调用方,如上所示。

关于ios - 在 objective-c 中抛出自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19217087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com