美文网首页
iOS开发中的异常处理

iOS开发中的异常处理

作者: 华子小筑 | 来源:发表于2016-11-17 16:33 被阅读498次

    程序运行有可能会出现错误,一旦遇到错误时该如何处理?在实际的开发中一般有两种错误处理的方式:通过函数返回值解决错误问题,另外一种是异常捕获;而后一种错误处理的方式目前被广泛的应用;那么在iOS开发中错误的处理是怎样的呢?

    Objective-C的异常处理
     - (void)viewDidLoad {
       [super viewDidLoad];
    
        @try {
              NSArray* testArray = @[@"1"];
              NSLog(@"%@",testArray[4]);
        } @catch (NSException *exception) {
            NSLog(@"%@",exception.reason);
        } @finally {
            // 即使出现异常,仍旧去处理的事务
        }
    }   
    
    • 上述代码块中@try...@catch代码块包裹可能出现异常的代码片段,异常处理后(日志记录等)在@finally块中可以继续执行其他事务操作;
    • 实际在使用Objective-C编程中很少会看见@try...@catch...@finally的这种处理模式;为什么很少使用异常处理?一种说法异常处理会带来性能上的损耗,另外一种说法是app开发过程中的crash是能够通过缜密的编程避免的,即使出现网络异常,文件操作失败等也不会导致闪退出现,可以通过日志系统反馈,同时Apple提供的API中也很难见到抛出异常的;
    • 知乎中详细介绍了为什么不建议使用try...catch可以仔细阅读了解一下
    App崩溃前如何进行异常抓取
    • NSSetUncaughtExceptionHandler:可以在程序运行终止之前进行日志的记录
    • 错误的信息包含函数堆栈调用、出错原因等
        - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        // Sets the top-level error-handling function where you can perform last-minute logging before the program terminates.
        NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
        return YES;
        }
        
        void UncaughtExceptionHandler(NSException *exception) {
            NSArray *callStack = [exception callStackSymbols];
            NSString *reason = [exception reason];
            NSString *name = [exception name];
            NSString *content = [NSString stringWithFormat:@"========异常错误报告========\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",name,reason,[callStack componentsJoinedByString:@"\n"]];
        }    
    
    Swift中的错误处理
    import Cocoa
    enum FileManagerError:Error{
        case filePathNotExist
        case fileAuthorityForbidden
    }
    class FileManager: NSObject {
    // 定义一个throwing函数对操作过程遇到的错误进行处理
      public  func openFile(filePath:String) throws -> Bool {
            if  !filePath.isEmpty {
               return true
            }else{
                throw FileManagerError.filePathNotExist
            }
        }
    }
    
    使用throwing函数抛出异常

    上述代码中openFile函数参数列表后加了throws关键字,在函数体中出现异常信息的时候就可以通过throw将异常抛出;然后通过try?将错误转化为可选值进行处理

     // 使用try?将错误转化成可选值来进行处理
    let fileManager = FileManager()
    let errorMessage = try?fileManager.openFile(filePath: "/var/library")
    print(errorMessage)
    
    使用do...catch

    使用do...catch处理异常信息需要catch住异常后罗列所有的异常信息后再一一进行业务处理

       // 使用 do...catch 列举所有的错误进行处理
    do {
        let message =  try fileManager.openFile(filePath: "/var/library")
        print(message)
    } catch FileManagerError.filePathNotExist {
        print("filePathNotExist")
    }catch FileManagerError.fileAuthorityForbidden {
        print("fileAuthorityForbidden")
    }catch{
        print("otherErrorMessage")
    }
    

    上述是介绍iOS开发中对于程序异常的处理;实际开发中会依赖三方服务类似:友盟错误统计、BugTags等三方服务来收集线上错误日志信息,同时目前的Apple在Xcode中也可以看到Appstore中下载App的崩溃信息,通过这些错误信息定位项目中引发问题的代码,最终完成bug的修复;

    相关文章

      网友评论

          本文标题:iOS开发中的异常处理

          本文链接:https://www.haomeiwen.com/subject/tngdpttx.html