Handling Exceptions

To catch an exception that may occur during the execution of a sequence of code, one can enclose the code in a try - catch block as follows
try
      ...
      throw exception_name;
      ...

catch  exception_name
      /* exception handling commands here */
end
where exception_name is an identifier used to represent the exception. All the names of exceptions form a global name space and are independent from local or global variable names. For example
function T = rctrap(f, a, b, n)
   x = [a, b];
   try
      y = f(x);
   catch no_vec
      // f is not vectorized; proceed accordingly
      
   end
      // f is vectorized; ...
   ...
end
hump = map x -> y
    if x.length != 1
         throw no_vec;
    end
    // other stuff
end
In this example, the function hump is not vectorized and throws an exception no_vec if called with a non-scalar. The function rctrap takes a function as the first argument and expects it to be vectorized. It catches the no_vec exception and does not perform the computations if the argument passed to it throws the error.

At present, errors caught by the interpreter are not (yet) exceptions and cannot be caught. Example of such errors are index out of bound error, undefined data attribute, etc.. When such errors occur, the interpreter returns to the user-interactive level, and the variables at the interactive level and global variables are left with uncertain values. This might be an inconvenience but it's possible to write throw/catch blocks to manually detect, throw, and handle these errors and bypass the interpreter's automatic error handling mechanism.

oz 2009-12-22