Error Handling

Handle runtime errors gracefully with try-catch blocks.

Try-Catch Blocks

kode
try {
    let result = divide(10, 0)
    print(result)
} catch (e) {
    print("Error caught: ${e}")
}
// Error caught: division by zero

Error Types

kode
enum Error {
    DivisionByZero,
    InvalidInput(reason: string),
    NotFound(resource: string),
    Unknown(message: string)
}

fn divide(a: int, b: int) -> Result<int, Error> {
    if (b == 0) {
        return Result.Error(Error.DivisionByZero)
    }
    return Result.Success(a / b)
}

Error Handling with Result Type

kode
let result = divide(10, 2)

match (result) {
    Result.Success(value) => print("Result: ${value}"),
    Result.Error(error) => print("Error occurred")
}

Safe Division Function

kode
fn safeDivide(a: int, b: int) int {
    try {
        return a / b
    } catch (e) {
        print("Error: ${e}")
        return -1
    }
    return 0
}

print(safeDivide(10, 2))   // 5
print(safeDivide(10, 0))   // Error: division by zero  →  -1

Defer Statement

defer schedules cleanup code to run before function returns:

kode
fn riskyOp() {
    defer { print("cleanup done") }
    print("doing work...")
}

riskyOp()
// doing work...
// cleanup done