在我们编写Objective-C程序时,最好的编程实践是指能预测程序中可能出现的问题。为此,你可以测试使程序异常终止的条件并处理这些情况, 可能要记录一条消息并完全终止程序,或者采取其他正确措施。以避免错误为例,在程序运行时执行测试可以避免向对象发送未识别的消息。当试图发送这类未识别 消息时,程序通常会立即终止并抛出一个异常。
看看下面的代码,Fraction类中未定义任何名为noSuchMethod的方法。当你编译程序时,就会得到相关警告消息。
|
#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; } |
-[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 |
@ try { statement statement ... } @ catch (NSException *exception) { statement statement ... } |
下面的代码演示了异常处理,紧跟着的是程序的输出。
#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! |