如果在catch块中抛出异常,是否会执行finally块?

时间:2012-12-28 23:20:22

标签: objective-c exception-handling

  

可能重复:
  does code in finally get run after a return in objective-c?

考虑这个Objective C伪代码块:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

@try {
    throw [[NSException alloc] init];
}
@catch (NSException *e) {
    throw e;
}
@finally {
    [pool drain];
}

游泳池会被排空吗?或者throw块中的@catch是否会使该代码无法访问?我觉得游泳池应该被耗尽,但我无法通过这种或那种方式找到文件。

是的我可以编写一些代码并对其进行测试,但目前这是不可行的。

由于

2 个答案:

答案 0 :(得分:4)

Yes (docs)

  

与本地@catch异常处理程序关联的@finally块   在@throw导​​致下一个更高的异常处理程序之前执行   被调用。

有关内存管理的更多说明,请参阅链接文档页面的最底部。在你的例子中你是“OK”,因为异常本身并不是作为你在finally块中消耗的池的一部分自动释放的。但如果没有人释放它,你可能会泄漏该异常。

(但在某些情况下,异常生命周期似乎有些含糊不清,请参阅:What is the lifecycle of an object caught in a @catch block?

答案 1 :(得分:2)

来自https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Exceptions/Tasks/HandlingExceptions.html

@finally — Defines a block of related code that is subsequently executed whether an exception is thrown or not.

但它没有说明catch块中的异常。 听起来合乎逻辑的是这个例外并不合适。

我做了一个简单的程序来检查:

import <Foundation/Foundation.h>

int main(int argc, char **argv)
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init] ;

    int result = 0  ;

    @try {
            @throw [NSException exceptionWithName:@"Exception" reason:@"@try" userInfo:nil];
    }
    @catch (id exception) {
            @throw [NSException exceptionWithName:@"Exception" reason:@"@catch" userInfo:nil];
    }
    @finally {
            NSLog(@"Finally");
    }

    [pool release]  ;
    return result   ;
}

只需编译并执行:

$ gcc -framework Foundation -fobjc-exceptions test.m
$ ./a.out 
2012-12-29 00:39:21.667 a.out[86205:707] *** Terminating app due to uncaught exception 'Exception', reason: '@catch'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff8e3050a6 __exceptionPreprocess + 198
    1   libobjc.A.dylib                     0x00007fff8e56e3f0 objc_exception_throw + 43
    2   a.out                               0x0000000107d48d47 main + 359
    3   libdyld.dylib                       0x00007fff90b4e7e1 start + 0
)
libc++abi.dylib: terminate called throwing an exception
Abort trap: 6