我想使用+[NSException exceptionWithName:reason:userInfo:]
。
但是我应该为参数 Name:
使用什么字符串?
异常名称在项目中是否应该唯一?
或者我可以对我的所有异常使用@"MyException"?
而且我不知道异常名称是干什么用的。
异常名称用在什么地方?
最佳答案
您可以在 @catch (NSException *theErr)
中使用名称。
@catch (NSException *theErr)
{
tst_name = [theErr name];
if ([tst_name isEqualToString:@"name"])
}
what string should I use for argument Name:?
任何有意义的东西。
Should exception name be unique in the project?
没有。
Or I can use @"MyException" for all of my exception?
是的,但您应该使用有意义的名称。
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
NSNumber *tst_dividend, *tst_divisor, *tst_quotient;
// prepare the trap
@try
{
// initialize the following locals
tst_dividend = [NSNumber numberWithLong:8];
tst_divisor = [NSNumber numberWithLong:0];
// attempt a division operation
tst_quotient = [self divideLong:tst_dividend by:tst_divisor];
// display the results
NSLog (@"The answer is: %@", tst_quotient);
}
@catch (NSException *theErr)
{
// an exception has occured
// display the results
NSLog (@"The exception is:\n name: %@\nreason: %@"
, [theErr name], [theErr reason]);
}
@finally
{
//...
// the housekeeping domain
//...
}
}
- (NSNumber *)divideLong:(NSNumber *)aDividend by:(NSNumber *)aDivisor
{
NSException *loc_err;
long loc_long;
// validity check
loc_long = [aDivisor longValue];
if (loc_long == 0)
{
// create and send an exception signal
loc_err = [NSException
exceptionWithName:NSInvalidArgumentException
reason:@"Division by zero attempted"
userInfo:nil];
[loc_err raise]; //locate nearest exception handler,
//If the instance fails to locate a handler, it goes straight to the default exception handler.
}
else
// perform the division
loc_long = [aDividend longValue] / loc_long;
// return the results
return ([NSNumber numberWithLong:loc_long]);
}
关于iphone - 在 Objective-C 中,我应该为 NSException 的异常名称使用什么名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12914070/