Errors in Scilab

// In Scilab, error handling is typically done using try-catch blocks
// and custom error messages.

// Define a function that may return an error
function [result, err] = f(arg)
    if arg == 42 then
        result = -1;
        err = msprintf("can't work with 42");
    else
        result = arg + 3;
        err = [];
    end
endfunction

// Define sentinel errors as strings
ErrOutOfTea = "no more tea available";
ErrPower = "can't boil water";

// Function that may return different types of errors
function err = makeTea(arg)
    if arg == 2 then
        err = ErrOutOfTea;
    elseif arg == 4 then
        // In Scilab, we can't wrap errors, so we'll just return a new error message
        err = msprintf("making tea: %s", ErrPower);
    else
        err = [];
    end
endfunction

// Main execution
for i = [7, 42]
    try
        [r, e] = f(i);
        if ~isempty(e) then
            disp("f failed: " + e);
        else
            disp("f worked: " + string(r));
        end
    catch
        disp("An unexpected error occurred");
    end
end

for i = 0:4
    try
        err = makeTea(i);
        if ~isempty(err) then
            if err == ErrOutOfTea then
                disp("We should buy new tea!");
            elseif strindex(err, ErrPower) ~= [] then
                disp("Now it is dark.");
            else
                disp("unknown error: " + err);
            end
        else
            disp("Tea is ready!");
        end
    catch
        disp("An unexpected error occurred");
    end
end

In Scilab, error handling is typically done using try-catch blocks. The concept of returning errors as separate values is not as idiomatic as it is in Go. Instead, we use conditional statements to check for error conditions and return error messages as strings.

Here’s a breakdown of the changes:

  1. The f function returns two values: the result and an error message (if any).

  2. Sentinel errors are defined as simple strings.

  3. The makeTea function returns an error message (or an empty string if no error).

  4. In the main execution, we use try-catch blocks to handle potential errors.

  5. Instead of errors.Is, we use string comparison (==) for exact matches and strindex for partial matches.

  6. We use disp for printing output instead of fmt.Println.

  7. String concatenation is done using the + operator.

This code demonstrates error handling in Scilab, showing how to return, check, and handle different types of errors. While it doesn’t have the same level of sophistication as Go’s error handling, it achieves similar functionality using Scilab’s features.