捕获异常的问题

时间:2010-07-16 08:56:12

标签: objective-c exception try-catch

我正在制作基于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 个答案:

答案 0 :(得分:1)

我认为@finally胜过其他任何东西。基本上,永远不会从@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不会从你身下消失(假设你使用的是ref计数而不是GC)。