Prev: Looping Statements

Error-Handling Statements

The catch statement allows you to indicate how errors should be handled in a block. You can use this statement when you anticipate that an error might occur for reasons other than your programming errors. For instance, you may anticipate being denied permission to perform an operation, and use a catch statement to handle this error explicitly. You can also use the catch statement to make sure that cleanup operations are performed if an error occurs.

The catch statement has the following syntax:

catch error code, error code, ...
    body-statement
with handler
    handler-statement
You can substitute the keyword any for the list of errors to indicate that you wish to catch all errors. You can leave out the with handler and the handler statement if you do not wish to do anything in the handler.

If an error listed in the error list is thrown inside body-statement, the interpreter will execute the handler rather than aborting the method. After the handler is done, control continues after the end of the catch statement, as if body-statement had completed with no errors.

Inside the handler, you can use the function error() to determine the error code which triggered the handler, the function error_arg() to retrieve the error argument specified by throw() if one weas given, and the function traceback() to retrieve a list of strings describing the propagation of the error down the call stack. You can use the function rethrow() to continue propagating an error.

Here is an example of how you might use a catch statement to intelligently handle a ~methodnf error from the list_method() function:

catch ~methodnf {
    code = list_method(method_name);
} with handler {
    .tell("There is no method named " + tostr(method_name) + ".");
}
Note that critical expressions (see Error-Handling Expressions) inside body-statement will override the behavior of the catch statement. For more detail on errors in C--, see Errors.