首页 > 移动平台 > 详细

在ios开发中使用 try 和 catch 来捕获错误。

时间:2014-04-16 16:05:21      阅读:571      评论:0      收藏:0      [点我收藏+]

ios中很少用到try 和catch

简单的来说,Apple虽然同时提供了错误处理(NSError)和异常处理(exception)两种机制,但是Apple更加提倡开发者使用NSError来处理程序运行中可恢复的错误。而异常被推荐用来处理不可恢复的错误。


原因有几个,在非gc情况下,exception容易造成内存管理问题(文档有描述即使是arc下,也不是安全的);exception使用block造成额外的开销,效率较低等等,另外这也的确是Cocoa开发者的习惯。

1,抛出错误的代码

    //如果返回的报文是错误信息,则抛出错误  
       if([outParams count] <= 0)  
       {  
           [NSException raise:@"WebService error" format:@"%@", returnJson4SOAP];  
       }  

2,在调用中捕获错误代码

    //从soap 信息中解析出CusotmerDetail 对象  
        @try  
        {  
            customerDetail = [[[SoapRtnJsonParser alloc] init] parse2CustomerDtail:[returnSoapXML dataUsingEncoding:NSUTF8StringEncoding]];  
        }@catch (NSException * e) {  
            NSLog(@"Exception: %@", e);  
            UIAlertView * alert =  
            [[UIAlertView alloc]  
             initWithTitle:@"错误"  
             message: [[NSString alloc] initWithFormat:@"%@",e]  
             delegate:self  
             cancelButtonTitle:nil  
             otherButtonTitles:@"OK", nil];   
            [alert show];  
            [alert release];  
            return;  
        }  


在ios开发中使用 try 和 catch 来捕获错误。,布布扣,bubuko.com

在ios开发中使用 try 和 catch 来捕获错误。

原文:http://blog.csdn.net/x32sky/article/details/23753597

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!