Recover in Chapel

Chapel provides a way to recover from errors using the try and catch statements. This is similar to exception handling in other languages.

use IO;

// This function throws an error
proc mayThrow() throws {
    throw new Error("a problem");
}

proc main() {
    try {
        mayThrow();
    } catch e {
        writeln("Recovered. Error:\n", e.message());
    }

    // This code will run, as the error was caught
    writeln("After mayThrow()");
}

In this example, we define a function mayThrow() that throws an error. In the main() function, we use a try-catch block to handle the error.

The try block contains the code that might throw an error. If an error is thrown, the execution immediately jumps to the catch block.

In the catch block, we can access the thrown error through the variable e. We print out a message along with the error’s message.

After the try-catch block, the program continues its normal execution. This means that unlike in some languages where an uncaught exception would terminate the program, Chapel allows us to recover from errors and continue execution.

To run this program:

$ chpl recover.chpl
$ ./recover
Recovered. Error:
a problem
After mayThrow()

This demonstrates how Chapel’s error handling mechanism allows us to gracefully recover from errors and continue program execution.