Objective-C中使用@try处理异常
来源:互联网 发布:学电脑编程能干什么 编辑:程序博客网 时间:2024/05/16 13:48
转载自: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块按顺序捕获并处理各种异常。
0 0
- 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)
- 策略路由基础命令(Linux)分享
- HoloGraphLibrary 源码解析
- Linux 学习day01-day02
- linux 剪文件
- Maven 聚合与继承
- Objective-C中使用@try处理异常
- Unique Subsets
- window.ShowModalDialog使用详解
- c/c++产生随机数
- 黑马程序员——总结第一次面试遇到的问题
- CircularFloatingActionMenu 源码解析
- HDU 1087 Super Jumping! Jumping! Jumping! (线性dp)
- C++一些注意点之new和malloc
- shell数组与字符串操作