swift语言点评十八-异常与错误

1、错误类型与枚举的结合

  1. enum VendingMachineError: Error {
  2. case invalidSelection
  3. case insufficientFunds(coinsNeeded: Int)
  4. case outOfStock
  5. }
  1. throw VendingMachineError.insufficientFunds(coinsNeeded: 5)

 

2、异常捕获与栈展开

Error handling in Swift resembles exception handling in other languages, with the use of the trycatch 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{}

 

 

 

posted @ 2018-04-08 11:23  zzfx  阅读(157)  评论(0编辑  收藏  举报