@try 後面的大括弧用來放可能會發生錯誤的程式碼, @catch 依據例外的型態 (type) 進行處理, @finally 則是無論例外是否發生都會執行的部份。
舉例如下
#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;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名: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
沒有留言:
張貼留言