Catch Exception

When an exception is thrown via a throw statement, evaluation of the script halts and the Engine returns with Err(Box<EvalAltResult::ErrorRuntime>) containing the exception value that has been thrown.

It is possible, via the trycatch statement, to catch exceptions, optionally with an error variable.

// Catch an exception and capturing its value
try
{
    throw 42;
}
catch (err)         // 'err' captures the thrown exception value
{
    print(err);     // prints 42
}

// Catch an exception without capturing its value
try
{
    print(42/0);    // deliberate divide-by-zero exception
}
catch               // no error variable - exception value is discarded
{
    print("Ouch!");
}

// Exception in the 'catch' block
try
{
    print(42/0);    // throw divide-by-zero exception
}
catch
{
    print("You seem to be dividing by zero here...");

    throw "die";    // a 'throw' statement inside a 'catch' block
                    // throws a new exception
}

Re-Throw Exception

Like the trycatch syntax in most languages, it is possible to re-throw an exception within the catch block simply by another throw statement without a value.

try
{
    // Call something that will throw an exception...
    do_something_bad_that_throws();
}
catch
{
    print("Oooh! You've done something real bad!");

    throw;          // 'throw' without a value within a 'catch' block
                    // re-throws the original exception
}

Catchable Exceptions

Many script-oriented exceptions can be caught via trycatch.

Error typeError value
Runtime error thrown by a throw statementvalue in throw statement
Arithmetic errorobject map
Variable not foundobject map
Function not foundobject map
Module not foundobject map
Unbound thisobject map
Data type mismatchobject map
Assignment to a calculated/constant valueobject map
Array/string/bit-field indexing out-of-boundsobject map
Indexing with an inappropriate data typeobject map
Error in property accessobject map
for statement on a type without a type iteratorobject map
Data race detectedobject map
Other runtime errorobject map

The error value in the catch clause is an object map containing information on the particular error, including its type, line and character position (if any), and source etc.

When the no_object feature is turned on, however, the error value is a simple string description.

Non-Catchable Exceptions

Some exceptions cannot be caught.

Error typeNotes
System error – e.g. script file not foundsystem errors are not recoverable
Syntax error during parsinginvalid script
Custom syntax mismatch errorincompatible Engine instance
Script evaluation metrics exceeding limitssafety protection
Script evaluation manually terminatedsafety protection