美文网首页
Error Handing

Error Handing

作者: 夜雨聲煩_ | 来源:发表于2017-12-27 18:43 被阅读0次
  • 使用枚举来定义多种error情况,遵循Error协议,并使用throw抛出对应错误情况

    //Representing and Throwing Errors
    enum VendingMachineError:Error {
        case invalidSelection
        case insufficientFunds(coinsNeeded: Int)
        case outOfStock
    }
    throw VendingMachineError.insufficientFunds(coinsNeeded: 5)
    
  • 使用guard配合抛出相应异常

    //Propagating Errors Using Throwing Functions
    struct Item {
        var price: Int
        var count: Int
    }
    
    class VendingMachine {
        var inventory = [
            "Candy Bar" : Item(price: 12, count: 7),
            "Chips" : Item(price: 10, count: 4),
             "Pretzels" : Item(price: 7, count: 11),
        ]
        var coinsDeposited = 0
      
        func vend(itemNamed name: String) throws {
            guard let item = inventory[name] else {
                throw VendingMachineError.invalidSelection
            }
            guard item.count > 0 else {
                throw VendingMachineError.outOfStock
            }
            guard item.price <= coinsDeposited else {
                throw VendingMachineError.insufficientFunds(coinsNeeded: item.price - coinsDeposited)
            }
          
            coinsDeposited -= item.price
            var newItem = item
            newItem.count -= 1
            inventory[name] = newItem
    
            print("Dispensing \(name)")
            
        }
      }
    
  • 使用try传递异常

    func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
        let snackName = favoriteSnacks[person] ?? "Candy Bar"
        try vendingMachine.vend(itemNamed: snackName)
    }
    
  • 使用do+try执行带有抛出异常的方法,使用catch捕获异常并加以处理

    var vendingMachine = VendingMachine.init()
    vendingMachine.coinsDeposited = 1
    do {
        try buyFavoriteSnack(person: "Alice", vendingMachine:       vendingMachine)
    } catch VendingMachineError.invalidSelection {
        print("Invalid Selection.")
    } catch VendingMachineError.outOfStock {
        print("Out of Stock")
    } catch VendingMachineError.insufficientFunds(let coinNeeded) {
        print("Insufficient funds. Please insert an additional \(coinNeeded) coins")
    }
    
  • 使用try?将返回变为可选

    //Converting Error to Optional Values
    func somtThrowingFunction() throws -> Int {
      
    }
    let x = try? somtThrowingFunction()
    let y : Int?
    do {
        try y = try somtThrowingFunction()
    } catch  {
        y = nil
    }
    
  • 使用try?同意处理多种throw错误结果处理相同时的简写

    func fetchData() -> Data? {
        if let data = try? fetchDataFromDisk() { return data }
        if let data = try? fetchDataFromSever() { return data }
        return nil 
    }
    
  • 使用try!确定不会错误时强制拆包

    //Disabling Error Propagation
    let photo = try! loadImage(atPath: "./Resources/John Appleseed.jpg")
    
  • 使用defer标记代码段保证无论是throw error还是break均会在defer出现的区域末尾执行代码段

    //Specifying Cleanup Actions
    func processFile(filename: String) throws {
        if exists(filename) {
            let file = open(filename)
            defer {
                close(file)
            }
            while let line = try file.readline() {
                // Work with the file.
            }
            // close(file) is called here, at the end of the scope.
        }
    }
    

    使用defer标记close操作,使需要在if段落末尾执行的close语句写在前面对应open,保证执行open就一定会执行close操作

  • 一段代码

    enum learningError: Error {
        case noMethod
        case noReading
        case noTool(toolName: String)
    }
    
    func iosDev(method: Bool, style: Bool, hasTool: Bool) throws{
        guard method else {
            throw learningError.noMethod
        }
        guard style else {
            throw learningError.noReading
        }
        guard hasTool else {
            throw learningError.noTool(toolName: "noMacBook")
        }
    }
    
    do {
        try iosDev(method: true, style: true, hasTool: false)
        print("is cool")
    } catch learningError.noMethod {
        print("no method")
    } catch learningError.noReading {
        print("no reading")
    } catch learningError.noTool(let name) {
        print("no", name)
    } catch {
        //加入空catch关闭
        //否则会报错:Errors thrown from here are not handled because the   enclosing catch is not exhaustive
    }
    
    if let result = try?iosDev(method: false, style: true, hasTool: true) {
        print("success")
    } else{
        print("failure")
    }
    

相关文章

  • Error Handing

    使用枚举来定义多种error情况,遵循Error协议,并使用throw抛出对应错误情况//Representing...

  • Swift - Error Handing

    响应错误以及从错误中恢复的过程 抛出、捕获、传递、操作可回复错误 表示与抛出错误 Swift 中,错误用遵循 Er...

  • RxSwift #06 | Error handing

    Managing errors 在应用程序中比较常见的 error 有: No Internet connecti...

  • 13B 异常处理

    //error_handing/*try{if(有异常情况)throw 数据;}监视数据是否被抛出catch (类...

  • Swift5 - note1

    Swift 2 Error handing 增强 guard语法 协议支持扩展 Swift 3 新的GCD和Cor...

  • Error Handing in swift3

    错误处理机制,在swift中的异常,必须在Controller级别给处理掉,不能再次往上抛出。 Handing E...

  • Rust中的错误处理机制

    [TOC] Rust中的错误处理机制 在大多数现代语言中,都拥有一套完善的错误处理机制(error handing...

  • Adhere to

    Handing in there every day.

  • Handing asynchronous results

    Handing asynchronous results Make controllers asynchronou...

  • Teaching in Thailand

    The first picture depicts a group of us handing out prize...

网友评论

      本文标题:Error Handing

      本文链接:https://www.haomeiwen.com/subject/feeugxtx.html