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.
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
.
Note 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:
This will output:
Remember 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.