1、错误类型与枚举的结合
enum VendingMachineError: Error {
case invalidSelection
case insufficientFunds(coinsNeeded: Int)
case outOfStock
}
throw VendingMachineError.insufficientFunds(coinsNeeded: 5)
2、异常捕获与栈展开
Error handling in Swift resembles exception handling in other languages, with the use of the try
, catch
and throw
keywords. Unlike exception handling in many languages—including Objective-C—error handling in Swift does not involve unwinding the call stack, a process that can be computationally expensive. As such, the performance characteristics of a throw
statement are comparable to those of a return
statement.
3、异常的传播:异常链
Only throwing functions can propagate errors. Any errors thrown inside a nonthrowing function must be handled inside the function.
func vend(itemNamed name: String) throws
nonthrowing function:异常传播的终结者。
局部处理与传播策略
The catch
clauses don’t have to handle every possible error that the code in the do
clause can throw. If none of the catch
clauses handle the error, the error propagates to the surrounding scope.
传播的简化:
You use try?
to handle an error by converting it to an optional value. If an error is thrown while evaluating the try?
expression, the value of the expression is nil
.
try!:切断错误传播链条,生产运行错误。
If an error actually is thrown, you’ll get a runtime error.
4、资源清理:defer{}