error handling


Error Handling - The Swift Programming Language (Swift 5.6)
throwsを作成する場所:矢印の前
func canThrowErrors() throws -> String
実施方法
  • enum Errorプロトコル
  • を使用
  • エラー
  • を投げ出す
  • 関数のthrows→関数内部でthrowsを教える
  • tryの後にthrows関数
  • を作成
    関数が内部でthrows関数を呼び出す場合は、throwsを記述する必要があります.
  • 最終エラー処理do catch
  • enum VendingMachineError: Error {
        case invalidSelection
        case insufficientFunds(coinsNeeded: Int)
        case outOfStock
    }
    
    class VendingMachine {
        . . .
        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)
            }
    
            . . .
        }
    }
    
    func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
        let snackName = favoriteSnacks[person] ?? "Candy Bar"
        try vendingMachine.vend(itemNamed: snackName)
    }
    catch文に条件を表示する
    do {
        try expression
        statements
    } catch pattern 1 {
        statements
    } catch pattern 2 where condition {
        statements
    } catch pattern 3, pattern 4 where condition {
        statements
    } catch {
        statements
    }
    func eat(item: String) throws {
        do {
            try vendingMachine.vend(itemNamed: item)
        } catch VendingMachineError.invalidSelection, VendingMachineError.insufficientFunds, VendingMachineError.outOfStock {
            print("Invalid selection, out of stock, or not enough money.")
        }
    }
    try?
    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 .
    func someThrowingFunction() throws -> Int {
        // ...
    }
    
    let x = try? someThrowingFunction()
    
    let y: Int?
    do {
        y = try someThrowingFunction()
    } catch {
        y = nil
    }