O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Catching Errors

To handle errors, Swift uses a control construct you have not yet seen: do/catch, with at least one try statement inside of the do. We will explain in a moment. First, modify evaluate(_:) to use this control flow to handle errors coming from lex().

Listing 20.13 Error handling in evaluate(_:)

...
func evaluate(_ input: String) {
    print("Evaluating: \(input)")
    let lexer = Lexer(input: input)

    do {
        let tokens = try lexer.lex()
        print("Lexer output: \(tokens)")
    } catch {
        print("An error occurred: \(error)")
    }
}

What do all these new keywords mean? do introduces a new scope, much like an if statement. Inside of the do scope, you can write code as normal, like calling print(). In addition, you can call functions ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required