Custom Errors in AngelScript
Custom errors can be implemented in AngelScript by creating a custom class that inherits from the Exception
class. Here’s an example that demonstrates this concept:
class argError : Exception
{
int arg;
string message;
argError(int arg, const string &in message)
{
this.arg = arg;
this.message = message;
}
string get_message() override
{
return arg + " - " + message;
}
}
int f(int arg)
{
if (arg == 42)
{
throw argError(arg, "can't work with it");
}
return arg + 3;
}
void main()
{
try
{
int result = f(42);
print("Result: " + result);
}
catch (argError &e)
{
print("Caught argError:");
print("Arg: " + e.arg);
print("Message: " + e.message);
}
catch (Exception &e)
{
print("Caught other exception: " + e.message);
}
}
In this example, we define a custom argError
class that inherits from the Exception
class. It has two properties: arg
and message
. We override the get_message()
method to provide a custom error message format.
The f
function demonstrates how to throw our custom error when a specific condition is met (in this case, when the argument is 42).
In the main
function, we use a try-catch block to handle exceptions. We first try to catch our custom argError
, and if it’s not caught, we catch any other Exception
.
To run this program, you would typically save it in a file with a .as
extension and use an AngelScript interpreter or embed it in a host application that supports AngelScript.
This example demonstrates how to create and use custom errors in AngelScript, providing a way to handle specific error conditions in your code.