zoukankan      html  css  js  c++  java
  • 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{}

     

     

     

  • 相关阅读:
    关于extern的用法
    建立CMenu菜单项,实现选中菜单项点击左键响应事件
    数据库常用语句
    圆周率的计算
    C++11中list特有版本的算法
    使用istream迭代器来输入输出数据
    C++中函数重载和函数覆盖的区别
    外置接口请求
    JSON转指定复杂对象
    FastDFS优化
  • 原文地址:https://www.cnblogs.com/feng9exe/p/8743893.html
Copyright © 2011-2022 走看看