從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