ios中很少用到try 和catch
简单的来说,Apple虽然同时提供了错误处理(NSError)和异常处理(exception)两种机制,但是Apple更加提倡开发者使用NSError来处理程序运行中可恢复的错误。而异常被推荐用来处理不可恢复的错误。
原因有几个,在非gc情况下,exception容易造成内存管理问题(文档有描述即使是arc下,也不是安全的);exception使用block造成额外的开销,效率较低等等,另外这也的确是Cocoa开发者的习惯。
1,抛出错误的代码
1
2
3
4
5
|
//如果返回的报文是错误信息,则抛出错误
if
([outParams count] <=
0
)
{
[NSException raise:@
"WebService error"
format:@
"%@"
, returnJson4SOAP];
}
|
2,在调用中捕获错误代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//从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
;
}
|