Objective-C 快速導覽 - 例外處理

例外處理 (exception handling) 為控制程式發生錯誤後的機制, Objective-C 使用 @try 、 @catch 與 @finally 三個指令進行例外處理。



@try 後面的大括弧用來放可能會發生錯誤的程式碼, @catch 依據例外的型態 (type) 進行處理, @finally 則是無論例外是否發生都會執行的部份。


舉例如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#import <Foundation/Foundation.h>
 
@interface Demo: NSObject
@end
 
@implementation Demo
@end
 
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
    Demo *d = [[Demo alloc] init];
    @try {
        [d do_something];
    }
    @catch (NSException * e) {
        NSLog(@"something wrong");
    }
    @finally {
        NSLog(@"finally");
    }
  
    [pool drain];
    return 0;
}
 
 
/* 《程式語言教學誌》的範例程式
   檔名:exception.m
   功能:Objective-c 程式範例
   作者:張凱慶
   時間:西元 2013 年 4 月 */


編譯執行,結果如下



中英文術語對照
例外處理exception handling
型態type


您可以繼續參考
例外處理
協定
類目


相關目錄
Objective-C 快速導覽
Objective-C 教材
首頁



參考資料
Programming with Objective-C: About Objective-C
Programming with Objective-C: Working with Objects

沒有留言: