NSException:错误处理机制---调试中以及上架后的产品如何收集错误日志

Objective-C也有类似于java的异常处理机制---@try @catch @finally,捕获的异常是封装在NSException对象中的。

NSException中有三个重要的变量name,reason,userInfo。

//系统提供了很多异常可以直接使用
FOUNDATION_EXPORT NSString * const NSGenericException;
FOUNDATION_EXPORT NSString * const NSRangeException;
FOUNDATION_EXPORT NSString * const NSInvalidArgumentException;
FOUNDATION_EXPORT NSString * const NSInternalInconsistencyException;

FOUNDATION_EXPORT NSString * const NSMallocException;

FOUNDATION_EXPORT NSString * const NSObjectInaccessibleException;
FOUNDATION_EXPORT NSString * const NSObjectNotAvailableException;
FOUNDATION_EXPORT NSString * const NSDestinationInvalidException;
    
FOUNDATION_EXPORT NSString * const NSPortTimeoutException;
FOUNDATION_EXPORT NSString * const NSInvalidSendPortException;
FOUNDATION_EXPORT NSString * const NSInvalidReceivePortException;
FOUNDATION_EXPORT NSString * const NSPortSendException;
FOUNDATION_EXPORT NSString * const NSPortReceiveException;

FOUNDATION_EXPORT NSString * const NSOldStyleException;
也可以自定义NSException

+ (NSException *)exceptionWithName:(NSString *)name reason:(NSString *)reason userInfo:(NSDictionary *)userInfo;
- (instancetype)initWithName:(NSString *)aName reason:(NSString *)aReason userInfo:(NSDictionary *)aUserInfo NS_DESIGNATED_INITIALIZER;

NSException的用法---捕获对象不存在的异常

    @try {
        //正常的代码
    }
    @catch (NSException *exception) {
        if ([[exception name] isEqualToString:NSObjectInaccessibleException]) { //如果对象不存在了
            NSLog(@"Object have not exits"); //打印下
        } else {
            [exception raise];//抛给未处理异常函数去处理
        }
    }

 
  
 
  

所有未处理的异常应该捕获,作为程序运行的反馈,所以需要一个总的处理函数,系统给我们提供了一个方法设置方法NSSetUncaughtExceptionHandler

在AppDelegate中加入处理方法

void UncaughtExceptionHandler(NSException *exception) {
    NSArray *stackSymbols = [exception callStackSymbols];
    NSArray *stackReturnAddress = [exception callStackReturnAddresses];
    NSString *reason = [exception reason];
    NSString *name = [exception name];
    
    NSString *url = [NSString stringWithFormat:@"=============异常崩溃报告=============\nname:\n%@\nreason:\n%@\ncallStackSymbols:\n%@\nstackReturnAddress:\n%@",
                     name,reason,[stackSymbols componentsJoinedByString:@" "],[stackReturnAddress componentsJoinedByString:@" "]];
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Exception.txt"];
    [url writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    //除了可以选择写到应用下的某个文件,通过后续处理将信息发送到服务器等
    //还可以选择调用发送邮件的的程序,发送信息到指定的邮件地址
    //或者调用某个处理程序来处理这个信息
}
 
  
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);  //处理函数
    return YES;
}

专业的Crash统计工具

http://try.crashlytics.com


你可能感兴趣的:(错误和异常处理,Foundation)