Swift异常处理
在Swift里,抛出的异常必须继承Error这个协议。那么这个协议是什么呢?
按住command再点击Error我们可以看到,
public protocol Error {
}
extension Error {
}
显然这个协议是空的,之所以还会有个空扩展,就是官方为了强调这个协议的确是空的,
只是为了标记错误的。
然后下面是我自己的例子,非常简单
enum numTest: Int, Error {
case _0, _1, _2, _3
case nothing = 999
}
func errorTest(by num: Int) throws -> String {
switch num {
case 0:
throw numTest._0
case 1:
throw numTest._1
case 2:
throw numTest._2
case 3:
throw numTest._3
case 10:
throw numTest.nothing
default:
return "OK" + " \(num)"
}
}
for i in 0...10 {
do {
try print(errorTest(by: i))
}catch numTest._0 {
print("wrong 0")
}catch numTest._1 {
print("wrong 1")
}catch numTest._2 {
print("wrong 2")
}catch numTest._3 {
print("wrong 3")
}catch {
print("unknow")
}
}
最后运行结果
wrong 0
wrong 1
wrong 2
wrong 3
OK 4
OK 5
OK 6
OK 7
OK 8
OK 9
unknow