iphone - 在 Objective-C 中,我应该为 NSException 的异常名称使用什么名称?

标签 iphone objective-c

我想使用+[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]);
}

看看Understanding Exceptions and Handlers in Cocoa

关于iphone - 在 Objective-C 中,我应该为 NSException 的异常名称使用什么名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12914070/

相关文章:

iphone - 动画化 UIView 过渡,例如将点扩展为圆圈

ios - 适用于 iOS 投票应用的最佳 BaaS

ios - 删除中间 View 时自动布局折叠空间

iphone - 在 UITableViewCell 和 UITableViewController 之间传递数据?

iOS 从云存储中选择图像

iphone - 使用 NSCoder 初始化静态单例对象

ios - 如何在xcode中通过调用栈查找相关代码?

ios - 使用单个数据源的多个 UIView

iphone - 如何限制可以在 iPhone 上的 HTML5 数字输入字段中输入的字符数

iphone - 在 MKAnnotationView 中更新图像