Error Handling

    A Panic is an irrecoverable error, and will occur when there is a logic issue in your code. Panics will cause the whole program to crash, and execution will be terminated.

    Running the above script, you’ll get:

    • Syntax error.
    • Integer division by zero.
    • Index out of bounds.
    • Attempt to call a value that is not a function.
    • Missing or exceeding arguments in function call.

    Recoverable errors may be expressed through values of the error type. This is a special type in the language, and it is the only which cannot be expressed through a literal. Values of the error type can only be created using the std.error function, which expects a string description and a arbitrary context:

    One can then check whether the function has returned an error:

    1. let result = check_limit(11)
    2. if std.type(result) == "error" then
    3. std.print("Error: ", result)
    4. else
    5. std.print("Success: ", result)
    6. end

    Examples of errors should be recoverable:

    • Insufficient permission
    • Invalid format
    • Command not found
    • Command returned non-zero exit status

    The try (?2) operator may be used to early return from a function if an error occurs. It is nothing but syntax sugar for an if expression, and therefore it may be used in any expression:

    1. function safe_div_mod(x, y)
    2. if y == 0 then
    3. std.error("division by zero", nil)
    4. else
    5. end
    6. end
    7. # The following are equivalent:
    8. function foo()
    9. let result = safe_div_mod(5, 0)
    10. let value = if std.type(result) == "error" then
    11. return result
    12. else
    13. result
    14. end
    15. std.print(value)
    16. end
    17. function bar()
    18. let value = safe_div_mod(5, 0)?
    19. std.print(value) # this won't be executed, as `?` will trigger an early return.
    20. end
    21. # The `?` operator may be used in any expression:
    22. function run()
    23. end

    If you’re familiar with both languages, Hush‘s try operator might feel like the unholy child of Rust’s operator and Go’s if err != nil { return err }.