2010-07-16 98 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