轉載自:http://www.itivy.com/iphone/archive/2011/12/20/iphone-objective-c-try-catch-statement.html
Objective-C中使用@try處理異常
這一篇我們主要來講講Objective-C中的@try塊來處理異常,與@try結合一起的有@catch、@finally。文章非常基礎,希望對初學者有所幫助。
在我們編寫Objective-C程序時,最好的編程實踐是指能預測程序中可能出現的問題。爲此,你可以測試使程序異常終止的條件並處理這些情況,可能要記錄一條消息並完全終止程序,或者採取其他正確措施。以避免錯誤爲例,在程序運行時執行測試可以避免向對象發送未識別的消息。當試圖發送這類未識別消息時,程序通常會立即終止並拋出一個異常。
看看下面的代碼,Fraction類中未定義任何名爲noSuchMethod的方法。當你編譯程序時,就會得到相關警告消息。
1
2
3
4
5
6
7
8
9
10
11
|
#import
“Fraction.h” int main
( int argc,
char *argv
[]) { NSAutoreleasePool
* pool = [[NSAutoreleasePool alloc] init]; Fraction
*f = [[Fraction alloc] init]; [f
noSuchMethod]; NSLog
(@”Execution continues!”); [f
release]; [pool
drain]; return 0; } |
1
2
3
4
5
6
7
8
9
10
11
12
|
-[Fraction
noSuchMethod]: unrecognized selector sent to instance 0x103280 ***
Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason:
‘*** -[Fraction noSuchMethod]: unrecognized selector sent to
instance 0x103280’ Stack:
( 2482717003, 2498756859, 2482746186, 2482739532, 2482739730 ) Trace/BPT
trap |
1
2
3
4
5
6
7
8
9
10
|
@ try { statement statement ... } @ catch (NSException
*exception) { statement statement ... } |
下面的代碼演示了異常處理,緊跟着的是程序的輸出。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#import
“Fraction.h” int main
( int argc,
char *argv
[]) { NSAutoreleasePool
* pool = [[NSAutoreleasePool alloc] init]; Fraction
*f = [[Fraction alloc] init]; @ try { [f
noSuchMethod]; } @ catch (NSException
*exception) { NSLog(@”Caught
%@%@”, [exception name], [exception reason]); } NSLog
(@”Execution continues!”); [f
release]; [pool
drain]; return 0; } |
1
2
3
4
|
***
-[Fraction noSuchMethod]: unrecognized selector sent to instance 0x103280 Caught
NSInvalidArgumentException: *** -[Fraction noSuchMethod]: unrecognized
selector sent to instance 0x103280 Execution
continues! |
這是一個非常簡單的例子,演示瞭如何在程序中捕獲異常。可以使用@finally塊包含是否執行拋出異常的@try塊中的語句代碼。
@throw指令允許你拋出自己的異常。可以使用該指令拋出特定的異常,或者在@catch塊內拋出帶你進入類似如下代碼塊的異常:
@throw;
自行處理異常後(例如,可能是在執行清除工作後)可能需要這麼做。然後便可以讓系統處理其餘的工作。最後,可以使用多個@catch塊按順序捕獲並處理各種異常。