Swift throws 处理
在Objective-C中,我们用NSError 处理错误信息.
比如coredata 中
#pragma mark - Core Data Saving support
- (void)saveContext {
// 避免 循环调用 get方法,所以 创建 临时 指针 ,指向 self.managedObjectContext
NSManagedObjectContext *managedObjectContext = self.backgroudContext;// 创建 临时数据库
if (managedObjectContext != nil) {
NSError *error = nil;
// 判断条件1 判断是否 改变
// 判断条件2 判断是否保存成功,当临时数据库改变并且保存失败的时候才会执行以下操作,打印error 并 终止程序
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
我们设置error指针,并用来接收方法可能产生的错误.
因为swift版本原因,在2.0之前用的一直是OC 的NSError处理. 在swift2.0 引出了 throws 错误处理机制.
swift 对所有的throws方法都做了限制,必须进行错误处理.
而swift的错误处理可以归结位一个流程: throws >> do > try >> catch
比如我们经常用到的 将data 序列化成 字典 或者 数组
let data:Data = Data()
let dic : NSDictionary?
do {
try dic = (JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSDictionary)
} catch let e {
print("数据出错: \(e)")
}
如果想知道throws更深层次的知识 .插播一下 喵神的博客
顺便说一下 try! 和 try?
如果你确定try的语句不会出现错误. 就执行try!. 这样程序不会进行错误判断. 但是一旦报错必定crash
如果try语句可能会报错, 就乖乖try catch 进行异常捕捉.
自定义错误类型 Error
用Xcode 戳进Error的文档解释.可以看到一段很长的官方解释 和 用例
用option查看 Error,也能看到一段简明扼要的说明
Summary
A type representing an error value that can be thrown.
Declaration
protocol Error
Discussion
Any type that declares conformance to the Error protocol can be used to represent an error in Swift’s error handling system.
Because the Error protocol has no requirements of its own, you can declare conformance on any custom type you create.
说白了就是 遵守 Error 就可以自定义错误类型
随后写了一个简单用例.
import UIKit
enum NetError:Error {
case sunshine
case cloudy
case rainy
case snow
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do {
try weathertoHappy(e: "snow")
} catch let e {
switch e {
case NetError.cloudy :
print("cloudy")
default:
print("sunshine")
}
}
}
func weathertoHappy(e:String) throws {
if e == "cloudy" {
throw NetError.cloudy
}
if e == "rainy" {
throw NetError.rainy
}
if e == "snow" {
throw NetError.snow
}
}
}