从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
@Perception这可能重复不回答这个问题。该问题和文档清楚地表明finally子句在try块中是否存在异常,但没有提及如果从catch块抛出异常会发生什么。它可能被称为,但另一个问题并没有澄清这个问题。 – rmaddy
@Madbreaks从Eugene链接的文档看来,您应该调用“@throw”而不是“throw e”来重新抛出异常。如果你这样做的话,这个文档暗示(尽管没有明确说明)“终于”会被调用。 – rmaddy
请注意,您绝对不应该为了从中恢复而捕获异常。在iOS和OS X中,异常仅用于指示不可恢复的错误(只有极少数可怜的奇数情况)。 – bbum