“try”需要用“ do catch”捕捉异常,如果在“try”代码块中出现异常,程序会跳转到相应的“catch”代码块中执行异常处理逻辑,然后继续执行“catch”代码块后面的代码。
enum NormalError: Error {
case one
case two
case three
case four
}
func someFunction(words: String) throws -> String {
switch words {
case "one":
throw NormalError.one
case "two":
throw NormalError.one
case "three":
throw NormalError.one
case "four":
throw NormalError.one
default:
return "ok"
}
}
//如果在“try”代码块中出现异常,程序会跳转到“catch”代码块中执行异常处理逻辑。
do {
try someFunction(words: "five")
} catch {
print("An error occurred: \(error)")
}
“try?”是返回一个可选值类型,如果“try?”代码块中出现异常,返回值会是“nil”,否则返回可选值。可以在运行时判断是否有异常发生。
// 返回值是一个可选类型,如果执行正常的话就存在返回值,否则如果抛出错误的话返回值为nil
let result = try? say(words: "four")
// 可选绑定
if let res = try? doSomething(words: "four") {
}
else { print("出现错误") }
// 提前退出
guard let resu = try? say(words: "four") else { return }
“try!”类似于可选型中的强制解包,它不会对错误进行处理,如果“try!”代码块中出现异常,程序会在异常发生处崩溃。
let result = try! someFunction()
print("The result is \(result)")
print(try? divide(2,1))//divide 整数除法运算符(/)
// Optional(2.0)
print(try? divide(2,0))
// nil
print(try! divide(2,1))
// 2.0
print(try! divide(2,0))
// 崩溃