2010-07-16 76 views
0

我正在制作一个基于iphone的应用程序,并遇到捕获异常的问题。到目前为止,我从来没有与试捕捞的问题,但在这里......好:d捕获异常的问题

这里是一个没有捕获任何异常的代码:

- (void)updateView:(NSTimer*)t { 

    NSMutableDictionary *requestResult = [[[NSMutableDictionary alloc] init] autorelease]; 

    @try { 
     requestResult = [self.eqParam getParameters]; 
    } 
    @catch (MMConnectionFailed * e) { 
     [self performSelectorOnMainThread:@selector(noConnection) withObject:@"Could not reach server." waitUntilDone:YES]; 
    } 
} 

下侧方法抛出异常良好在调试模式下,如果出现异常,但在涉及此方法时,不会捕获任何内容。

任何线索?


UPDATE:

最后,我发现问题出在哪里了,但我仍然不知道为什么异常不在下杆抛出。我改变了我的getParameters方法的结尾。在这里:

- (NSMutableDictionary *)getParameters { 

    @try { 
     // be careful with NSMutableDictionary. Has to be used with setters to be correctly affected 
     lastResponse = [MMSoapMethods getEquipmentParametersWithUserString:user equipmentId:equipmentId]; 
    } 
    @catch (MMConnectionFailed * e) { 
     @throw e; 
    } 
    @finally { 
     if (self.lastResponse) { 
      return lastResponse; 
     }  
     else 
      return nil; 
    } 
} 

我只是删除了@finally周围的标签和异常被抛出。奇怪,不是吗?

+0

你也可以把Objective-C标签放在问题中。有可能你要么捕捉错误类型的异常,要么在try-section中没有任何代码抛出异常。 – Nubsis 2010-07-16 09:09:42

回答

1

我认为@终极胜过其他任何东西。基本上,永远不会从@finally块中返回一个值。

重构代码为getPArameters这样的:

- (NSMutableDictionary *)parameters // Objective-C naming convention - no get 
{ 

     // be careful with NSMutableDictionary. Has to be used with setters to be correctly affected 
     // your version did not retain the return result. This does, as long as the property lastResponse is retain 
     self.lastResponse = [MMSoapMethods getEquipmentParametersWithUserString:user equipmentId:equipmentId]; 
     return self.lastResponse; 

     // no need to catch an exception just so you can throw it again 
} 

我觉得上面的等价于你所得到的,只是它不returna值从finally块和lastReponse不会从下你消失(假设你正在使用ref计数而不是GC)。

+0

是的你是对的,我的代码有点笨拙......非常感谢你的回答,它是完美的! – 2010-07-16 14:57:28