enum someError: Error{ case someCase } enum VendingMachineError: Error { case invalidSelection case insufficientFunds(coinsNeeded: Int) case outOfStock } struct Item { var price: Int var count: Int } class VendingMachine { var inventory = [ "Candy Bar": Item(price: 12, count: 2), "Chips": Item(price: 10, count: 4), "Pretzels": Item(price: 7, count: 11) ] var coinsDeposited = 100 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)") } } let favoriteSnacks = [ "Alice": "Chips", "Bob": "Licorice", "Eve": "Pretzels", ] func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws { let snackName = favoriteSnacks[person] ?? "Candy Bar" try vendingMachine.vend(itemNamed: snackName) } var vendingMachine = VendingMachine() vendingMachine.coinsDeposited = 8 do { try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine) print("Success! Yum.") } 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.") } catch { print("Unexpected error: (error).") } */
結果
Playground execution terminated: An error was thrown and was not caught: ▿ VendingMachineError ▿ insufficientFunds : 1 element - coinsNeeded : 2
https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html
Swiftドキュメントの上記のエラー処理についていろいろやっていて、
書いてあることはだいたいわかるのですが、
エラーをスローして、それを捕捉しないとどうなるのか、と思い、上記コードを実行すると、
上記のようなエラーメッセージが出ました。
coinsDeposited(8)が"Chips"の単価(10)より少ないので
VendingMachineError.insufficientFunds(coinsNeeded: item.price - coinsDeposited)
がスローされるが、対応するcatch節をコメントしてみた、ということなのですが、
そこでこれはコンパイルエラーなのか、実行時エラーなのか、という疑問が浮かびました。
どっちでしょうか?
コンパイルエラーか、実行時エラーかの見分け方はあるのでしょうか?
これがわからないのは、そもそもコンパイルエラーと実行時エラーの定義がわかってないのだと思うのですが、
どこを見たら解決しますでしょうか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/30 03:54