Recover in Scilab

Our program demonstrates error handling and recovery. Here’s the full source code:

function mayPanic()
    error("a problem")
endfunction

function main()
    try
        mayPanic()
    catch
        [msg, num] = lasterror()
        disp("Recovered. Error:")
        disp(msg)
    end
    
    disp("After mayPanic()")
endfunction

main()

In this example, we define two functions:

  1. mayPanic(): This function simulates a critical error by calling the error() function.

  2. main(): This is our primary function that demonstrates error handling.

The main() function uses a try-catch block to handle potential errors:

try
    mayPanic()
catch
    [msg, num] = lasterror()
    disp("Recovered. Error:")
    disp(msg)
end

If an error occurs in mayPanic(), it will be caught by the catch block. The lasterror() function is used to retrieve the error message, which is then displayed.

After the try-catch block, we have a line that prints “After mayPanic()”. This line demonstrates that execution continues after recovering from the error.

To run the program, save it as a .sce file (e.g., error_recovery.sce) and execute it in Scilab:

--> exec('error_recovery.sce', -1)
Recovered. Error:
a problem
After mayPanic()

This output shows that the error was caught and handled, and the program continued execution after recovering from the error.

In Scilab, error handling is typically done using try-catch blocks, which serve a similar purpose to the recover functionality in some other languages. This allows for graceful error handling and prevents the entire program from crashing due to an unexpected error.