MAXScript provides simple exception-handling with the try expression, a simplified form of the C++ exception-handling scheme. The try expression lets you bracket a piece of code and catch any runtime errors. This allows you to respond appropriately or take corrective action, rather than let MAXScript halt the execution of your script and print an error message.
The syntax for the try expression is:
f = openFile "foo.dat"
while not eof f do read_some_data f
messageBox "bad data in foo.dat"
results = undefined
In this example, any errors in reading or processing the data in the read_some_data() function are trapped, then a Message box is displayed and some clean-up is done. This is a good example of a use for the simple error-trapping.
There is also an associated function, throw(), which can be used to generate your own runtime error and pass on an error you caught when doing some interim clean-up, or do a non-local jump.
It has the form:
If you have no intervening catches in your script, calling throw() with error message arguments will cause a runtime error to be signaled and MAXScript will report the error message using its standard error reporting. The optional second argument can be any value you want printed with the error message, perhaps the object involved in the error. This second argument can not be specified if the throw is in the body of a catch() and will generate a compile error if present.
If the try/catch is within another try expression, calling throw() will cause the catch expression associated with the outer try expression to be executed. If you have no intervening catches in your script, calling throw() will cause MAXScript to continue running the script from just after the top-most set of parenthesis surrounding the try/catch, or will stop the currently running script if there are no parenthesis surrounding the try/catch.
If you want to catch an error, perhaps to do some clean-up processing, and then pass the error on to outer handlers or MAXScript for error reporting, you can call throw() with no arguments. This throws the current error again and must only be done inside a catch expression. For example:
try ( i.x=1 ) -- will generate a run-time error
print "Bad Error" -- error message printed
try (i.pos=[0,0,0]) -- will also generate a run-time error
catch (throw()) -- throw() will cause outer catch
-- to execute
catch (print "Really Bad Error Occurred") -- error message printed
This method returns the text of the current exception. It is only useful inside a catch statement - if used outside a catch, it will return 'undefined'.
format "*** % ***\n" (getCurrentException())
*** -- Runtime error: AAAAA ***