What name should I use for exception name of NSException, in Objective-C?
iphone, objective-c
Solution
You can use the name in in `@catch (NSException *theErr)`.
@catch (NSException *theErr)
{
tst_name = [theErr name];
if ([tst_name isEqualToString:@"name"])
}
what string should I use for argument Name:?
Anything meaningful.
Should exception name be unique in the project?
No.
Or I can use @"MyException" for all of my exception?
Yes, but you should use meaningful names.
- (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]);
}
Take a look at Understanding Exceptions and Handlers in Cocoa
Problem
I want to use `+[NSException exceptionWithName:reason:userInfo:]`. But 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? And I don't know what exception name is used for. Where are exception names used?