Things go wrong in programs all the time.

A string is added to a number, a list is indexed beyond its end, a file that should be there is not. Teascript has no try and catch statements for these situations. Errors are raised by an ordinary function call and caught by another one, and everything else in this chapter follows this simple design.

This chapter explains what an error is, how to raise one, how to catch it, and, just as importantly, when it is better not to use errors at all.

Errors

When the interpreter’s VM reaches a situation in which it cannot continue, it raises an error.

The normal execution stops at that point, and the error travels up through the active function calls, abandoning each one, until it reaches a protected call. If there is none, the program ends; the standalone interpreter prints the error message to the standard error stream and exits with a non-zero status.

var list = [1, 2, 3]

print(list[10])         // error: the index is outside the list
print("never reached")

The second print never runs.

The error left the program before it could be reached.

An error carries a value, the error value, which describes what went wrong. Errors raised by the interpreter itself, such as the one above, carry a string with a message. Errors raised by your own code can carry any value at all, as we will see in a moment.

It is useful to tell two kinds of errors apart.

A syntax error is found when source code is compiled, before anything has run; the whole file is rejected, and not a single statement of it is executed.

A runtime error happens while the program is running, as in the example. The mechanisms below deal with the second kind; syntax errors in the program itself must simply be fixed, although code that is built at runtime can also be checked, as we will see.

Raising Errors

The function error raises an error.

It takes any value, which becomes the error value, and it never returns:

function withdraw(balance, amount)
{
    if amount > balance
    {
        error("insufficient funds")
    }
    return balance - amount
}

print(withdraw(100, 30))    // 70
print(withdraw(100, 300))   // error: insufficient funds

Since the error value can be anything, a program can raise a map to attach more information than a message alone, which the code that catches the error can then inspect:

error({ code = 404, message = "page not found" })

The function assert is a shorthand for the common case of checking a condition.

If its first argument is falsy it raises an error, using the second argument as the message, which should be a string; otherwise it does nothing and returns the first argument unchanged:

var n = assert(tonumber("42"), "not a number")
print(n)    // 42

assert(tonumber("forty-two"), "not a number")   // error: not a number

Returning its argument is what makes assert convenient to wrap around an expression, as above, instead of writing a separate if.

Raising an error is appropriate when the program has reached a state that its author did not plan for; a function called with arguments that make no sense, a broken assumption, a resource that was required and is not available. In these cases the code that detected the problem usually cannot decide what to do about it, and the error carries the decision upward.

Protected Calls

The function pcall calls another function in protected mode.

Whatever the function does, an error raised inside it will not propagate any further; pcall catches it. Its first argument is the function to call, and the remaining ones are passed to it as arguments:

function divide(a, b)
{
    if b == 0 { error("division by zero") }
    return a / b
}

var ok, result = pcall(divide, 10, 2)
print(ok, result)       // true 5

ok, result = pcall(divide, 1, 0)
print(ok, result)       // false division by zero

The result of pcall is always a list of two items, which is why it can be unpacked with a multi-variable declaration, as described in the chapter. The first item is a boolean telling whether the call succeeded. If it did, the second item is the value returned by the function. If it did not, the second item is the error value.

Notice that the second assignment in the example reuses the variable instead of declaring them again.

Using pcall Correctly

The function that is passed to pcall must be the function itself, not the result of calling it:

pcall(divide(1, 0))     // wrong: divide runs first, and its error is not caught
pcall(divide, 1, 0)     // right

In the first line the call to divide is evaluated before pcall is even entered, so there is nothing protecting it. When the work to be protected is more than a single call, wrap it in a lambda:

var ok, err = pcall(() => {
    var data = load_config()
    apply(data)
})

Methods can be passed directly, since a method obtained from an instance remains attached to it, as in pcall(account.withdraw, 50).

The first item of the result must always be checked.

Ignoring it silently discards the error, and the program carries on as if nothing had happened, which is usually worse than letting it stop:

var ok, value = pcall(risky)
if not ok
{
    print("risky failed: ${value}")
}

A protected call also does not extend to the file it appears in.

A syntax error in the program itself is found before pcall could run. For code that is created at runtime, however, the functions loadstring and loadfile compile source text and return it as a function, raising an error if it is not valid. Wrapping them in pcall lets a program check code it did not write, and the example at the end of the chapter does exactly that.

Rethrowing and Cleanup

Catching an error does not oblige a program to handle it.

If a function can do part of the work, for instance releasing a resource, but not decide what to do about the failure, it can catch the error, do its part, and raise the same error value again:

import io

function read_all(path)
{
    var f = io.open(path)
    var ok, result = pcall(() => f.read())
    f.close()               // always runs, success or not

    if not ok { error(result) }
    return result
}

Teascript has no finally block; this pattern plays its role. The file is closed whether or not the read succeeded, and the error, if any, continues on its way, unchanged.

Where to Catch

It is tempting to wrap everything in pcall, but an error that is caught too early is an error that nobody gets to see.

Catch errors where something meaningful can be done about them; at the boundary of a task that can be retried or skipped, at the point where a message can be shown to the user, or at the top of a long-running loop that must survive the failure of a single iteration. Everywhere else, let errors travel.

Errors as Values

Raising errors is not the only way to report that something went wrong, and for failures that are expected, it is often not the best one.

Reading a number from user input fails regularly, and that is not exceptional at all. Forcing every caller to wrap the call in pcall makes such code longer and more annoying to read.

Teascript’s own functions follow this idea.

tonumber returns nil when a string is not a number, readline returns nil at the end of a file, and get on a map returns nil, or a given default, for a missing key. The caller tests the result, and, thanks to the way or works, can often supply a fallback in the same expression:

var port = tonumber(text) or 8080

When nil is not enough, because the caller also needs to know why the operation failed, a function can return a list with both the result and the error. This uses the same unpacking as pcall, and the caller receives both values in separate variables:

function parse_age(text)
{
    var n = tonumber(text)
    if n == nil { return [nil, "not a number: ${text}"] }
    if n < 0 { return [nil, "an age cannot be negative"] }
    return [n, nil]
}

var age, err = parse_age("42")
if err == nil
{
    print("age is ${age}")
}
else
{
    print("invalid age: ${err}")
}

A function written this way never raises an error for bad input, and the failure is visible in the code that calls it, since the error value has to be looked at.

Choose one convention for a program, or for a module, and stick to it; mixing the order of the items, or sometimes returning a lone nil, makes the callers harder to write correctly.

The two approaches can also be combined.

A function that raises can be turned into one that returns them with a single pcall, at the place where the failure is expected, and conversely, a caller that cannot handle a returned error can raise it with error.

The choice between the two mechanisms comes down to who is expected to deal with the problem:

SituationMechanism
A value may be absent, and that is normalReturn nil
An operation fails regularly, and the caller needs the reasonReturn a list [value, error]
A mistake by the programmer, or a broken assumptionerror or assert
A failure that only a distant caller can handleerror, caught with pcall there
Running code that is not trusted, or not yet known to be validpcall around it

An Example

We conclude with a small interactive calculator.

It reads a line, treats it as an expression, and prints its value. It needs to survive anything the user types, which makes it a natural application of everything in this chapter; the code itself is built at runtime, so it must be compiled and run in two separate protected steps, and the two kinds of failure are reported differently.

// calc.tea
function compile(source)
{
    return pcall(loadstring, "print(" + source + ")", "<calc>")
}

while true
{
    var line = input("calc> ")
    if line == nil or line == "quit" { break }
    if line == "" { continue }

    var compiled, chunk = compile(line)
    if not compiled
    {
        print("syntax error: ${chunk}")
        continue
    }

    var ran, err = pcall(chunk)
    if not ran
    {
        print("runtime error: ${err}")
    }
}

The text typed by the user is wrapped in a call to print and compiled with loadstring.

This can fail with a syntax error, so it is protected, and the result is the usual pair: a flag, and either the compiled function or the message. Only if the compilation succeeded is the function run, again through pcall, so that an error in the expression itself does not end the program. The input function returns nil at the end of the input, which, together with the word quit, is how the loop ends.

$ tea calc.tea
calc> 6 * 7
42
calc> 2 ** 10
1024
calc> 6 *
syntax error: ...
calc> "tea" + 1
runtime error: ...
calc> quit

The text of each message is produced by the interpreter. Notice that the calculator keeps running after both failures, and that it can tell them apart simply because they happen in different protected calls.

Errors complete the part of the guide dedicated to the core of the language. The next part describes the data structures that most programs are built from, beginning with Data Structures.