Error Handling

AodhML uses explicit error types rather than exceptions. The Result<T, E> type forces callers to handle errors.

Result Type

fn divide(a: f64, b: f64) -> Result<f64, String> {
    if b == 0.0 {
        return Err("Division by zero")
    }
    return Ok(a / b)
}

Error Propagation (?)

The ? operator propagates errors automatically:

fn compute(x: f64, y: f64) -> Result<f64, String> {
    let a = divide(x, 2.0)?   // If Err, returns early
    let b = divide(y, 3.0)?   // If Err, returns early
    return Ok(a + b)
}

Handling Results

fn main() {
    match divide(10.0, 2.0) {
        Ok(result) => println("Result: ", result),
        Err(msg) => println("Error: ", msg),
    }

    // Or with unwrap (panics on error)
    let value = divide(10.0, 2.0).unwrap()

    // Or with a default
    let safe = divide(10.0, 0.0).unwrap_or(0.0)
}

Custom Error Types

type ShapeError = enum {
    Incompatible,
    NegativeDimension,
    BroadcastFailed,
}

fn reshape(tensor: Tensor<f32>, shape: [u32]) -> Result<Tensor<f32>, ShapeError> {
    for dim in shape {
        if dim == 0 {
            return Err(ShapeError::NegativeDimension)
        }
    }
    // ... reshape logic
    return Ok(result)
}