代码之家  ›  专栏  ›  技术社区  ›  Romain Piel

捕获异常时出现问题

  •  0
  • Romain Piel  · 技术社区  · 16 年前

    我正在制作一个基于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];
        }
    }
    

    在发生异常的情况下,较低的方法在调试模式下抛出良好的异常,但当涉及此方法时,不会捕获任何异常。

    有什么线索吗?


    更新:

    最后,我发现问题出在哪里,但我仍然不知道为什么异常没有被扔到较低的杠杆上。我改变了我的结局 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 周围的标记和异常被抛出。很奇怪,不是吗?

    1 回复  |  直到 16 年前
        1
  •  1
  •   JeremyP    16 年前

    我认为@最终胜过其他任何东西。基本上,永远不要从@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
    }
    

    我认为上面的内容与您所拥有的内容相同,只是它没有从finally块返回值,并且lastreponse不会从您下面消失(假设您使用的是引用计数而不是gc)。

    推荐文章