OWADVL OWADVL - 1 year ago 73
Swift Question

Swift 2.2 error handling by try block

I've just started to learn Swift couple of days ago. In my Xcode playground I have the following code:

//: Playground - noun: a place where people can play

import UIKit

enum VendingMachineError: ErrorType {
case InvalidSelection
case InsufficientFunds(coinsNeeded: Int)
case OutOfStock

func requestBeverage(code: Int, coins: Int) throws {
guard code > 0 else {
throw VendingMachineError.InvalidSelection
if coins < 2 {
throw VendingMachineError.InsufficientFunds(coinsNeeded: 3)
guard coins > 10 else {
throw VendingMachineError.OutOfStock

print("everything went ok")

try requestBeverage(-1, coins: 4)

If I try to run it, nothing happens. but I would expect to print "finished..." because in my logic, it tries to do something, fails, then the program would continue....

So the question is, why isn't the program continuing, and how can I tell the code to continue in case of error with as little words as possible?

Thanks in advance

Answer Source

You can catch all errors individually with do/catch:

do {
    try requestBeverage(-1, coins: 4)
} catch VendingMachineError.InvalidSelection {
    print("Invalid selection")
} catch VendingMachineError.OutOfStock {
    print("Out of stock")
} catch VendingMachineError.InsufficientFunds(let coinsNeeded) {
    print("You need \(coinsNeeded) more coins")
} catch {
    // an unknown error occured


Alternatively, use try? if you only care about whether an error is thrown, but not which one:

func requestSomeBeverage() {
    guard (try? requestBeverage(-1, coins: 4)) != nil else {
        print("An error has occured")


If you're absolutely sure an error will not be thrown, and you want to cause an exception when it does, use try! (but in most cases, don't):

try! requestBeverage(-1, coins: 4)