Error Handling
Vex represents recoverable failure and absence as values. Use the prelude Result<T, E> when an operation can fail with a meaningful error, and Option<T> when a value may simply be absent. Neither requires an import.
Return an error the caller can inspect
An error enum gives callers stable cases to match. Keep diagnostic text at the boundary that presents the failure:
enum DivisionError { ZeroDivisor, Overflow }
fn divide(left: i32, right: i32): Result<i32, DivisionError> {
if right == 0 { return Err(DivisionError.ZeroDivisor); }
if left == (-2147483647 - 1) && right == -1 {
return Err(DivisionError.Overflow);
}
return Ok(left / right);
}
fn main(): i32 {
match divide(20, 4) {
Ok(value) => { $println(value); },
Err(DivisionError.ZeroDivisor) => {
$println("cannot divide by zero"); return 1;
},
Err(DivisionError.Overflow) => {
$println("quotient is outside i32"); return 1;
},
};
return 0;
}Save this as division.vx and run vex run division.vx. It prints 5 and exits with status 0. Returning the quotient from main would instead use it as the process exit status. Integer division truncates the fractional part; this function handles both zero division and the signed minimum divided by -1.
Represent ordinary absence with Option
fn firstEven(left: i32, right: i32): Option<i32> {
if left % 2 == 0 { return Some(left); }
if right % 2 == 0 { return Some(right); }
return None;
}
fn main(): i32 {
match firstEven(3, 8) {
Some(value) => { $println(value); },
None => { $println("no even value"); },
};
return 0;
}This complete example prints 8 and exits 0. None is a typed absence, not an integer sentinel or a null raw pointer. See the Option API for borrowing, mapping, and extraction.
Propagate failure with ?
? extracts a success payload or returns the unsuccessful branch from the current function. The enclosing return type must support that propagation. For example, using divide and DivisionError from above:
fn calculate(): Result<i32, DivisionError> {
let first = divide(20, 4)?;
let second = divide(first, 2)?;
return Ok(second + 1);
}The successful result is Ok(3). If either division fails, the following statements are skipped and its error is returned. ? does not print an error, terminate the process, or provide a fallback. Keep the error type the same or convert it explicitly before propagation; see Result for mapErr and conversion guidance.
Option-returning functions can likewise propagate absence:
fn incrementEven(left: i32, right: i32): Option<i32> {
let value = firstEven(left, right)?;
return Some(value + 1);
}Choose fallback or early return deliberately
A match makes fallback evaluation and early return explicit:
fn requirePresent(value: Option<i32>): Result<i32, str> {
let inner = match value {
Some(inner) => inner,
None => return Err("missing value"),
};
return Ok(inner + 1);
}The prelude also provides ?? and !> operators. Follow the operand and callback signatures on the Option and Result pages. ?? supplies a fallback value; !> invokes a handler for the unsuccessful branch. Do not assume an ordinary fallback expression is lazy.
An !> handler supplies a replacement success payload. Its return exits the handler closure, not the enclosing function. For example, missing !> || { return 7; } produces 7 for an absent Option<i32>. A handler containing only return; returns unit and cannot initialize an i32. Use an outer match when failure must return from the caller.
Ownership is part of error handling
Matching or mapping a value can transfer its payload. Do not assume an owned Result<string, E> remains usable after a consuming helper call. Check whether a method receives self by value or by reference. The API pages spell out those receiver contracts; Copy examples alone do not establish how an owning payload behaves.
The prelude does not provide unwrap or expect on these types. When an invariant violation should stop execution, use an explicit panic branch. Handle expected user input and I/O failures as values. Error propagation still follows normal scope cleanup for owned values.
Null pointers belong at foreign boundaries
Use typed pointer constructors and isNull() at an FFI boundary. The following is a declaration sketch, not a complete allocation wrapper:
extern "LIBC" {
fn malloc(size: usize): Ptr<Opaque>
}
let pointer = malloc(64)
if pointer.isNull() { return 1 }A non-null result does not establish alignment, initialization, ownership, or how to free it. Keep those obligations together in a small wrapper and return an Option or Result to ordinary application code. See FFI and Raw Pointers.
Choosing a representation
| Situation | Prefer |
|---|---|
| Success or a meaningful failure | Result<T, E> |
| An ordinary missing value | Option<T> |
| Return a compatible failure from the caller | ? |
| Distinct recovery for different errors | match |
| Supply a default success value | ?? or an explicit match |
| A raw null pointer crosses a foreign ABI | Ptr<T>.isNull() at the boundary |
Handle an error where the program can make a useful decision. Lower layers should preserve enough information for that decision; the outer application can select an exit status, report the problem, or retry under a bounded policy.
Next steps
Ownership in practice
- Ownership workflows — complete borrowed-parser and owned-report examples