OC 异常处理

1、@try 语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@try {

// Code that can potentially throw an exception 可能会抛出异常的代码块

statement
. . .

} @catch (NSException *exception) {

// Handle an exception thrown in the @try block 处理 @try 块抛出的异常

NSLog(@"%@, %@", [exception name], [exception reason]);

statement
. . .

} @finally {

// Code that gets executed whether or not an exception is thrown 无论是否抛出异常都要被执行的代码块

statement
. . .
}
  • 当出现异常时,@catch 块被执行。包涵异常信息的 NSException 对象作为参数传递给这个块。name 监测异常的名称,reason 方法给出原因(运行时系统还是会将原因自动输出)。
  • 在 @catch 块中的最后一条语句执行后,程序会立即执行之后的语句,程序并不会终止运行。

  • 在 iOS 开发时很少使用 try catch 错误处理机制,因为 iOS ARC 开发时,所有 retain, release, autorelease 都是编译自动增加的,一旦使用了 try catch,程序如果出现异常,系统没有办法准确的判断第几个语句出现问题,导致 retain, release 失衡,会造成内存泄漏。

文章目录
  1. 1. 1、@try 语句
隐藏目录