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

     

     

     

  • 相关阅读:
    微信小程序开发之普通链接二维码
    微信小程序之使用本地接口开发
    c# partial 分部类和分部方法
    .NET之美 第一部分C#语言基础
    Head First设计模式之命令模式
    Head First设计模式之责任链模式
    Head First设计模式之解释器模式
    Head First设计模式之迭代器模式
    Head First设计模式之中介者模式
    LeetCode 709. To Lower Case
  • 原文地址:https://www.cnblogs.com/feng9exe/p/8743893.html
Copyright © 2011-2022 走看看