NSError && NSException

来源:互联网 发布:mac清楚最近使用记录 编辑:程序博客网 时间:2024/06/05 22:59

NSError和NSException的异同:
NSError是非致命的,可恢复的错误。NSError 被捕获的问题是用户错误,通常可以通过错误信息中进行恢复,并且预期或可以预测的错误(如打开没有权限访问的文件)。
NSException是专为潜在的致命的程序错误,这些错误的设计意味着应用程序中存在潜大的缺陷,你没有正确地检查先决条件而执行某些操作(如试图访问数组索引超出其边界,试图改变不可改变的对象)
参考文章:Exception Programming Guide
参考博客:http://stackoverflow.com/questions/11100951/nsexception-and-nserror-custom-exception-error


NSException的成员属性与方法
成员:
– name 异常名字
– reason 出现异常的理由
– userInfo 包含应用具体异常信息

@property(readonly, copy) NSArray *callStackReturnAddresses 错误回调堆栈地址信息@property(readonly, copy) NSArray *callStackSymbols 

An array of strings describing the call stack backtrace at the moment the exception was first raised. The format of each string is determined by the backtrace_symbols() API

方法:
创建一个异常

+ exceptionWithName:reason:userInfo:

Creates and returns an exception object .

Declarat
+ (NSException *)exceptionWithName:(NSString *)name reason:(NSString *)reason userInfo:(NSDictionary *)userInfoameters
name
The name of the exception.
reason
A human-readable message string summarizing the reason for the exception.
userInfo
A dictionary containing user-defined information relating to the exception

创建并抛出异常
+ raise:format:
A convenience method that creates and raises an exception.

Declaration

OBJECTIVE-C
+ (void)raise:(NSString )name format:(NSString )format,, …
Parameters
name
The name of the exception.

format,
A human-readable message string (that is, the exception reason) with conversion specifications for the variable arguments that follow.


Variable information to be inserted into the formatted exception reason (in the manner of printf).

  • initWithName:reason:userInfo:
    Designated Initializer
    Initializes and returns a newly allocated exception object.

Declaration

SWIFT
init(name name: String, reason reason: String?, userInfo userInfo: [NSObject : AnyObject]?)

OBJECTIVE-C
- (instancetype)initWithName:(NSString )name reason:(NSString )reason userInfo:(NSDictionary *)userInfo

Parameters
name
The name of the exception.
reason
A human-readable message string summarizing the reason for the exception.
userInfo
A dictionary containing user-defined information relating to the exception
Return Value
The created NSException object or nil if the object couldn’t be created.

PS:

@interface ZhouCHong : NSObject@property (nonatomic, strong) NSString* name;@end@implementation ZhouCHong-(void)dealloc{    NSLog(@"%s",__FUNCTION__);}@endint main(int argc, const char * argv[]) {    @autoreleasepool {        int i=0;        NSArray *array=@[@"1"];        ZhouCHong* zc;        @try {            zc = [[ZhouCHong alloc] init];            zc.name = array[1];//此处会抛出数组越界异常,          //这后面的代码将不在执行            !!!!此处zc对象将不会释放,存在内存泄漏        }        @catch (NSException *exception) {            NSLog(@"%@",exception);//捕捉到异常,并处理        }        @finally {            i=100;        }        NSLog(@"%d",i);    }    return 0;}
0 0
原创粉丝点击