Handling Errors — Clean Language
← All tutorials
first-steps5 min

Handling Errors

Things go wrong. A user enters something unexpected, a calculation hits an impossible case, a resource isn't available. Clean Language gives you a clean, readable way to deal with it.

You raise an error with error(), and catch it with onError:

functions:
    integer divide(integer a, integer b)
        if b == 0
            error("Cannot divide by zero")
        return a / b

start:
    integer result = divide(10, 2) onError -1
    print(result.toString())

    integer bad = divide(10, 0) onError -1
    print(bad.toString())
5
-1

The onError -1 part means: if anything goes wrong, use -1 instead. No crash, no mystery — just a predictable fallback.

For more than just a fallback value, use onError: with a block:

functions:
    integer divide(integer a, integer b)
        if b == 0
            error("Cannot divide by zero")
        return a / b

start:
    integer result = divide(10, 0) onError:
        print("Something went wrong — using default")
        -1

    print(result.toString())
Something went wrong — using default
-1

The last line of the onError: block is the value that gets used as the result. You can do any amount of work — logging, cleanup — and then provide the fallback on the last line.

Quick recap

  • Use error("message") inside a function to raise an error
  • expression onError fallbackValue — catch and provide a simple fallback
  • expression onError: with a block — catch and run any code, last line is the fallback
  • Errors propagate up the call chain until something catches them
  • If nothing catches an error, the program stops with an error message
Copied!