error handling

김태현·2022년 2월 18일
0

swift

목록 보기
6/7
post-thumbnail

Error Handling - The Swift Programming Language (Swift 5.6)


throws 작성 위치 : 화살표 전에

func canThrowErrors() throws -> String

구현 방법

  1. enum에 Error 프로토콜 사용
  2. 에러를 throw
  3. 함수의 throws → 함수 내부에서 throw한다는 사실 알려줌
  4. try 뒤에 throws 함수 작성
  5. 어떤 함수가 throws 함수를 내부에서 호출하면 throws를 작성해야한다.
  6. 최종 error handle은 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
}
profile
iOS 공부 중

0개의 댓글