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:
The
f
function returns two values: the result and an error message (if any).Sentinel errors are defined as simple strings.
The
makeTea
function returns an error message (or an empty string if no error).In the main execution, we use try-catch blocks to handle potential errors.
Instead of
errors.Is
, we use string comparison (==
) for exact matches andstrindex
for partial matches.We use
disp
for printing output instead offmt.Println
.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.