ESC
Type to search...
S
Soli Docs

Error Handling

Try/catch/finally for exception handling, throw for raising errors.

Try / Catch / Finally

try / catch / finally

Handles exceptions with try/catch blocks, using end-delimited syntax just like if, while, and for.

# Basic try/catch
try
    let result = 10 / 0;
catch e
    print("Error: " + str(e));
end

# With finally (always runs)
try
    let data = read_file("config.sl");
    print(data);
catch e
    print("Failed: " + str(e));
finally
    print("Cleanup done");
end

# Try/finally without catch
try
    process_data();
finally
    close_connection();
end

Catch Variable Syntax

The catch variable can be written with or without parentheses:

# Without parentheses
try
    risky();
catch e
    print(e);
end

# With parentheses
try
    risky();
catch (e)
    print(e);
end

Throwing Exceptions

throw

Raises an exception that can be caught by a surrounding try/catch block.

def divide(a: Int, b: Int) -> Int
    if b == 0
        throw "Division by zero";
    end
    a / b
end

try
    let result = divide(10, 0);
catch e
    print("Caught: " + str(e));  # "Caught: Division by zero"
end

Brace Syntax

Try/catch also supports brace-delimited blocks, like all other control flow statements in Soli:

try {
    let result = risky_operation();
} catch (e) {
    print("Error: " + str(e));
} finally {
    cleanup();
}

Nested Try/Catch

Try/catch blocks can be nested for fine-grained error handling:

try
    print("Outer try");
    try
        throw "inner error";
    catch e
        print("Inner catch: " + str(e));
    end
    print("After inner try");
catch e
    print("Outer catch: " + str(e));
end