Objective-C中使用@try处理异常
来源:互联网 发布:家庭装修网络布置方案 编辑:程序博客网 时间:2024/04/29 23:36
在我们编写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!
- Objective-C中使用@try处理异常
- Objective-C中使用@try处理异常
- Objective-C中使用@try处理异常
- Objective-C中使用@try处理异常
- Objective-C中使用@try处理异常,防止程序崩溃
- Objective-C中异常处理
- 【IOS 开发学习总结-OC-22】★objective-c——使用@try 处理异常
- Objective-c异常处理
- objective-c 异常处理
- 在C语言中实现Try-Catch异常处理
- OC使用@try处理异常
- Visual C++异常处理机制原理与应用(四)——C/C++结构化异常处理之try-except异常处理的使用(中)
- Objective-c学习笔记07——异常处理(try catch)
- Java 中使用 try-catch-finally处理异常
- objective-c中的异常处理
- Objective-C - 异常处理(Exception)
- Objective-C - 异常处理(Exception)
- Objective-C - 异常处理(Exception)
- 深入理解JavaScript系列(4):立即调用的函数表达式
- javassist使用教程(jar破解)
- Android使用活动栏 —— 添加ActionBar项目
- 转码总结
- 深入理解JavaScript系列(5):强大的原型和原型链
- Objective-C中使用@try处理异常
- onResume时窗口无焦点
- ORACLE:Health Monitor
- 跳转页面
- 深入理解JavaScript系列(6):S.O.L.I.D五大原则之单一职责SRP
- 再论空指针检测问题
- 深入理解JavaScript系列(7):S.O.L.I.D五大原则之开闭原则OCP
- jquery文本框获得和失去焦点改变样式
- SIP协议