一. try catch
enum ErrorEnum : Error {
case errorString(String)
}
func chuFa(_ num1: Int, _ num2: Int)throws -> Int{
if num2 == 0 {
throw ErrorEnum.errorString("被除数不能为0")
}
return num1/num2
}
//好几种写法
do {
let ret = try chuFa(10, 0)
print(ret)
} catch let ErrorEnum.errorString(errorMsg){
print(errorMsg)
} catch {
print("其他异常")
}
do {
let ret = try chuFa(10, 0)
print(ret)
} catch let error as ErrorEnum{
print(error)
} catch {
print("其他异常")
}
do {
let ret = try chuFa(10, 0)
print(ret)
} catch is ErrorEnum{
print("ErrorEnum")
} catch {
print("其他异常")
}
do {
let ret = try chuFa(10, 0)
print(ret)
} catch let error{
switch error {
case let ErrorEnum.errorString(str):
print(str)
default:
print("其他类型的异常")
}
} catch {
print("其他异常")
}
try chuFa(10, 0) //errorString : "被除数不能为0"
try? chuFa(10, 0) //nil -> try? 抛出错误, 返回nil
//try! chuFa(10, 0) //崩溃 -> try! 抛出错误不处理的话,会崩溃
var bbbbb: Int?
do {
bbbbb = try chuFa(10, 0)
} catch {
bbbbb = nil
}
// throws 代表函数可能会抛出异常
// rethrows 函数本身不会抛出异常,但调用闭包参数抛出异常,那么它会将异常往上抛
//rethrows 和throws差不多
二. refer
//: # defer
// defer 美[dɪˈfɜːr] v.延期,推迟;听从,遵从(defer to)
// 用来定义以任何方式(抛错误 return等)离开代码块前必须执行的代码
// defer语句将延迟到当前作用域结束之前执行
print("-------------------------------------------------------------------------------------------")
func chuFa_1(_ num1: Int, _ num2: Int)throws -> Int{
print("进入到chufa_1")
if num2 == 0 {
throw ErrorEnum.errorString("被除数不能为0")
}
return num1/num2
}
var aaa: Int?
do {
defer{
print("666")
}
aaa = try chuFa_1(10, 0)
} catch let ErrorEnum.errorString(errMsg){
aaa = nil
print(errMsg)
}
/*
进入到chufa_1
666
被除数不能为0
*/
//解释: 虽然 print("666")这句话 在最上面,但是先不执行, 而是当前作用域结束之前执行