Error handling

Optionals, exceptions, exit codes and compile-time errors: which failure mechanism to reach for, and when each one is fatal.

vlatest

PickleScript has two ways to deal with failure, and they answer different questions.

An option is a T?, either a value or none. It is for expected absence: there is no first item, that file does not exist yet. It is an ordinary value, the caller unwraps it, and a none is not a failure.

An exception is a throw caught by a try / catch. It is for a failure you should not have to push onto every caller: a config file that will not parse, a request that must succeed. The payload is a string and it travels up the call chain until something catches it.

There is no Result type.

Options are T?

A ? after a type makes it optional. none is the empty case.

fn findFirst(items: List<int>) -> int? {
    for (i in items) {
        return i
    }
    return none
}

fn main() {
    let nums = [1, 2, 3]
    let found = findFirst(nums)
    if (let some(v) = found) {
        println("found {v}")
    } else {
        println("nothing")
    }
}

There is no Option<T> type name and no some(...) function, T? is the whole type, and if (let some(v) = x) is the only way to unwrap it.

if let unwraps, or does not

if (let some(v) = x) binds v only inside the then branch. The else branch runs when the value is none.

fn double(n: int) -> int? {
    if (n < 0) {
        return none
    }
    return n * 2
}

fn main() {
    let good = double(4)
    if (let some(v) = good) {
        println("doubled {v}")
    } else {
        println("negative")
    }

    let bad = double(-1)
    if (let some(v) = bad) {
        println("doubled {v}")
    } else {
        println("negative")
    }
}

?? supplies a default

The ?? operator returns the left side when it holds a value, and the right side when it is none. It is the short way to handle a missing value.

fn findFirst(items: List<int>) -> int? {
    for (i in items) {
        return i
    }
    return none
}

fn main() {
    println(findFirst([1, 2, 3]) ?? -1)   // 1
    println(findFirst([0]) ?? -1)        // 0
}

?? needs a default of the unwrapped type, not of the option type.

? propagates: and is fatal on none

? returns early from the current function when the value is none. The function's return type must be optional for this to type-check.

fn parsePort(s: string) -> int? {
    if (s == "") {
        return none
    }
    return 80
}

fn describe(s: string) -> string? {
    let port = parsePort(s)?
    return "listening on " + str(port)
}

fn main() {
    let ok = describe("any")
    if (let some(msg) = ok) {
        println(msg)
    } else {
        println("no port")
    }
}

Be careful: if the caller of describe uses ? too, a none keeps propagating until nothing handles it, and the process dies:

fn parsePort(s: string) -> int? {
    if (s == "") {
        return none
    }
    return 80
}

fn describe(s: string) -> string? {
    let port = parsePort(s)?          // unwraps a none, which is fatal
    return "listening on " + str(port)
}

// describe("") aborts the process here; see the note above.
fn main() {
    let r = describe("any")
    if (let some(msg) = r) {
        println(msg)
    } else {
        println("no port")
    }
}

That program prints:

fatal: pickle: unwrapped none value

? is a propagation tool, not an error mechanism. When a failure is expected and you want to keep running, use if let or ?? instead.

Exceptions

throw raises a failure carrying a string payload. It does not have to be caught where it happens: it travels up the call chain until a catch matches it.

fn boom() {
    throw "boom"
}

// The throw crosses the call to boom() and is caught in this frame.
fn guarded() -> string {
    try {
        boom()
        "unreachable"
    } catch (e) {
        "caught " + e
    }
}

guarded() returns "caught boom". The "unreachable" line never runs.

catch (e) binds the payload as a string. When you do not need it, write a bare catch:

try {
    risky()
} catch {
    recover()
}

A try yields a value in tail position

A try block is a statement, not a general expression. It produces a value only when it is the last thing in the enclosing block, and then the value is whichever arm ran:

fn describe(n: int) -> string {
    try {
        if (n > 0) {
            "positive"
        } else {
            "non-positive"
        }
    } catch (e) {
        "failed: " + e
    }
}

In tail position the try body is the function's result, so a value only comes from it there. Anywhere else it is just a statement.

finally runs on every path

finally is optional and independent of catch. It runs when the body completes, when a throw is caught, when a throw keeps propagating, and when the body leaves early with return, break or continue.

try {
    work()
} finally {
    cleanup()      // runs whichever way we leave
}

The ordering is exact, and worth relying on:

  • The catch runs before the finally.
  • A nested finally runs before the outer catch.
  • With several finally blocks in scope, the innermost runs first.
  • A try / finally with no catch does not catch. The throw keeps going.

A throw that nobody catches ends the program

With no catch anywhere on the call chain, the payload reaches the top of the program. It is written to stderr and the process exits with status 1:

uncaught exception: boom

How a throw actually travels

Worth knowing before reading runtime or compiler code: PickleScript does not unwind machine frames. Compiled frames carry no unwind information, so a throw cannot skip a frame without stranding the collector's shadow stack.

Propagation is cooperative instead. throw publishes the payload and raises a per-thread "pending" flag, then returns normally. The compiler emits a check after every call, and when the flag is set the enclosing function returns immediately. So every frame between the throw and the handler leaves normally and pops its own shadow frame, and the matching catch consumes the flag. The payload is rooted for exactly the window in which nothing else holds a reference to it.

Which one to reach for

Use an option when none is a normal outcome the caller should decide about. Use throw when the operation could not be carried out at all, and threading a T? back through every intermediate function would say nothing useful.

exit(code) is the one way to stop a program deliberately. It takes a numeric code and never returns.

Assertions

assert(cond) is available in every program. It checks a condition and aborts the process if it is false, useful in tests and in code that has been reasoned about, not for handling expected failures.

fn main() {
    assert(1 + 1 == 2)
    println("assert passed")
}

Compile-time errors are different

Syntax and type errors are reported by the compiler and stop the program before it runs. They are not values and cannot be caught:

fn main() {
    let n: int = "not a number"
    println(n)
}

The compiler rejects it before the program starts:

error[E0308] type mismatch in binding: expected `int`, found `string`
  = note: `string` does not satisfy `int`

A compile error is a bug you must fix. A none is a situation your program is expected to handle.

Next steps