您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页使用try和catch来捕获错误

使用try和catch来捕获错误

来源:二三娱乐

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 nil];

[alert show];

[alert release];

return;

}

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务