Error Handling

Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime.

Error Enum: Error Protocol을 채택한 Error Enum을 만든다.

enum VendingMachineError: Error {
    case invalidSelection
    case insufficientFunds(coinsNeeded: Int)
    case outOfStock
}

에러를 발생시키는 메소드 만들기

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

Error를 Catch하는 방법

🙃 01. do-catch

do {
    try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine)
} catch VendingMachineError.invalidSelection {
    print("Invalid Selection.")
} catch VendingMachineError.outOfStock {
    print("Out of Stock.")
} catch VendingMachineError.insufficientFunds(let coinsNeeded) {
    print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.")
}

🙃 02. Converting to Optional Value

let x = try? someThrowingFunction()

Sample Code

import Foundation
import UIKit

enum NumberCheckType: Error {
    case negativeNum
    case biggerNum
    case noData
}

class HandlingErrorViewController: UIViewController {

    func isSmallNum(baseNum: Int, targetNum: Int?) throws -> Int {
        guard let compareNum = targetNum else {
            throw NumberCheckType.noData
        }
        
        if baseNum < 0 || compareNum < 0 {
            throw NumberCheckType.negativeNum
        }
        
        if compareNum > baseNum {
            throw NumberCheckType.biggerNum
        }
        
        return compareNum
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        do {
            let num = try isSmallNum(baseNum: 10, targetNum: -1)
            print(num)
        }catch NumberCheckType.biggerNum {
            print("error.biggerNum, 더 작은 숫자를 입력해주세요")
        }catch NumberCheckType.noData {
            print("noData, 값을 입력해주세요")
        }catch NumberCheckType.negativeNum {
            print("negativeNum, 양수를 입력해주세요")
        }catch {
          print("설마 다른 에러가 있을까요?")
        }
    }

}