Panic in AngelScript
Our first example demonstrates how to handle unexpected errors or situations in AngelScript. While AngelScript doesn’t have a built-in panic function like some languages, we can create a similar mechanism using exceptions.
void main()
{
// We'll use exceptions throughout this site to check for
// unexpected errors. This is the only program on the
// site designed to throw an exception.
throw("a problem");
// A common use of exceptions is to abort if a function
// returns an error value that we don't know how to
// (or want to) handle. Here's an example of
// throwing an exception if we get an unexpected error when creating a new file.
File @file = File();
if (!file.open("/tmp/file", "w"))
{
throw("Failed to create file: " + file.getErrorString());
}
}Running this program will cause it to throw an exception, print an error message, and exit with a non-zero status.
When the first throw in main is executed, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first throw.
$ angelscript panic.as
Exception: a problemNote that unlike some languages which use exceptions for handling of many errors, in AngelScript it’s often preferable to use error-indicating return values where possible, and reserve exceptions for truly exceptional circumstances.
To catch exceptions and handle them gracefully, you can use a try-catch block:
void main()
{
try
{
throw("a problem");
}
catch
{
print("Caught exception: " + getExceptionInfo().message + "\n");
}
}This will output:
Caught exception: a problemRemember that while exceptions can be useful for handling unexpected errors, they should be used judiciously. Overuse of exceptions can make code harder to understand and maintain.
Comments powered by Disqus