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{}

 

 

 

转载于:https://www.cnblogs.com/feng9exe/p/8743893.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值