9.1 抛出异常
2020-06-09 本文已影响0人
LucXion
主动抛出异常,抛出而不处理会使程序直接中断
func showError(parama:Bool)throws {
if parama {
}else {
throw MyError.QuoteError
}
}
try showError(parama: false) // 主动在函数内抛出异常:throws、try
if true {
}else {
throw MyError.SystemError // 主动在函数外部抛出异常
}
do-catch捕获异常、try?捕获异常
var a:String?
var b:String = ""
func MyFountion()throws ->Int{
print("执行")
if let temp = a {
b = temp
}else {
throw MyError.SystemError
}
return 4
}
var temp = try? MyFountion()
if let _ = temp {
print("执行成功")
}else {
print("执行失败")
}
do {
try MyFountion()
} catch MyError.QuoteError {
print("捕获错误类型")
} catch MyError.SystemError{
print("捕获到了")
} catch {
print("崩溃但没捕获")
}
延迟执行操作
func MyFountion(){
defer {
print("延迟执行结构,可以在任意情况下导致的函数执行中断或结束后执行,如抛出异常、return等")
}
}