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:
let result = check_limit(11)
if std.type(result) == "error" then
std.print("Error: ", result)
else
std.print("Success: ", result)
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:
function safe_div_mod(x, y)
if y == 0 then
std.error("division by zero", nil)
else
end
end
# The following are equivalent:
function foo()
let result = safe_div_mod(5, 0)
let value = if std.type(result) == "error" then
return result
else
result
end
std.print(value)
end
function bar()
let value = safe_div_mod(5, 0)?
std.print(value) # this won't be executed, as `?` will trigger an early return.
end
# The `?` operator may be used in any expression:
function run()
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 }
.