- Objective-C 基础
- Objective-C - 首页
- Objective-C - 概述
- Objective-C - 环境设置
- Objective-C - 程序结构
- Objective-C - 基本语法
- Objective-C - 数据类型
- Objective-C - 变量
- Objective-C - 常量
- Objective-C - 运算符
- Objective-C - 循环
- Objective-C - 决策
- Objective-C - 函数
- Objective-C - 块
- Objective-C - 数字
- Objective-C - 数组
- Objective-C - 指针
- Objective-C - 字符串
- Objective-C - 结构体
- Objective-C - 预处理器
- Objective-C - Typedef
- Objective-C - 类型转换
- Objective-C - 日志处理
- Objective-C - 错误处理
- 命令行参数
- 高级 Objective-C
- Objective-C - 类与对象
- Objective-C - 继承
- Objective-C - 多态
- Objective-C - 数据封装
- Objective-C - 分类
- Objective-C - 伪装
- Objective-C - 扩展
- Objective-C - 协议
- Objective-C - 动态绑定
- Objective-C - 复合对象
- Obj-C - Foundation 框架
- Objective-C - 快速枚举
- Obj-C - 内存管理
- Objective-C 有用资源
- Objective-C - 快速指南
- Objective-C - 有用资源
- Objective-C - 讨论
Objective-C 错误处理
在 Objective-C 编程中,错误处理是通过 Foundation 框架 中提供的 NSError 类来实现的。
NSError 对象封装了比仅使用错误代码或错误字符串更丰富和更可扩展的错误信息。NSError 对象的核心属性包括错误域(由字符串表示)、特定于域的错误代码以及包含应用程序特定信息的用户信息字典。
NSError
Objective-C 程序使用 NSError 对象来传达有关运行时错误的信息,用户需要了解这些信息。在大多数情况下,程序会在对话框或表单中显示此错误信息。但它也可以解释这些信息,并要求用户尝试从错误中恢复,或者尝试自行更正错误。
NSError 对象包含以下内容:
域 - 错误域可以是预定义的 NSError 域之一,也可以是描述自定义域的任意字符串,并且域不能为 nil。
代码 - 错误的错误代码。
用户信息 - 错误的 userInfo 字典,userInfo 可以为 nil。
以下示例演示如何创建自定义错误
NSString *domain = @"com.MyCompany.MyApplication.ErrorDomain";
NSString *desc = NSLocalizedString(@"Unable to complete the process", @"");
NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
NSError *error = [NSError errorWithDomain:domain code:-101 userInfo:userInfo];
以下是上面错误示例的完整代码,作为对指针的引用传递:
#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
-(NSString *) getEmployeeNameForID:(int) id withError:(NSError **)errorPtr;
@end
@implementation SampleClass
-(NSString *) getEmployeeNameForID:(int) id withError:(NSError **)errorPtr {
if(id == 1) {
return @"Employee Test Name";
} else {
NSString *domain = @"com.MyCompany.MyApplication.ErrorDomain";
NSString *desc =@"Unable to complete the process";
NSDictionary *userInfo = [[NSDictionary alloc]
initWithObjectsAndKeys:desc,
@"NSLocalizedDescriptionKey",NULL];
*errorPtr = [NSError errorWithDomain:domain code:-101
userInfo:userInfo];
return @"";
}
}
@end
int main() {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
SampleClass *sampleClass = [[SampleClass alloc]init];
NSError *error = nil;
NSString *name1 = [sampleClass getEmployeeNameForID:1 withError:&error];
if(error) {
NSLog(@"Error finding Name1: %@",error);
} else {
NSLog(@"Name1: %@",name1);
}
error = nil;
NSString *name2 = [sampleClass getEmployeeNameForID:2 withError:&error];
if(error) {
NSLog(@"Error finding Name2: %@",error);
} else {
NSLog(@"Name2: %@",name2);
}
[pool drain];
return 0;
}
在上面的示例中,如果 id 为 1,则返回名称,否则设置用户定义的错误对象。
当编译并执行上述代码时,会产生以下结果:
2013-09-14 18:01:00.809 demo[27632] Name1: Employee Test Name 2013-09-14 18:01:00.809 demo[27632] Error finding Name2: Unable to complete the process
广告