Exceptions handling
Handling errors at runtime
AddyScript's try-catch-finally statement provides an elegant way to handle errors that occur during script execution. You'll typically use this statement when you want to execute a sequence of statements that are likely to generate errors and you don't want your script to be interrupted because of those errors. Here's how to use it:
Example:
Let the user enter an expression that we will evaluate. The expression entered by the user may be wrong.
Remarks:
- The catch and finally blocks are both optional, but you cannot omit them both at the same time. There must always be a catch or a finally block in a try-catch-finally statement.
- If your finally block contains a goto statement, make sure that the statement does not attempt to jump out of the block (i.e., you are not allowed to jump out of a finally block).
- A return statement cannot appear in a finally block.
- The contents of the finally block are always executed, whether an error occurs or not.
Raising errors
To raise an error, simply use the following syntax:
throw new Exception('name', 'message');
or simply
throw new Exception('message');
or more simply
throw 'message';
Of course, you don't have to throw an instance of the Exception class. But if you throw something else, it will be used as the exception message.
Throw expressions
There are some cases where a throw statement can be used as an expression (called a throw expression):
-
In a ternary conditional expression (?:), any of the results can be a throw expression.
-
In a logical expression with the ?? operator, the right operand can be a throw expression. That syntax has a similar effect to using the postfix ! operator but it gives us control over the message of the exception that is thrown when the first operand is empty.
Example -
As seen in the pattern matching section, a switch expression can throw an exception when a pattern is matched.
Try-with-resource
There is a special variant of the try-catch-finally statement that has an argument associated with it. This argument is called a resource. The resource is intended to be immediately released (meaning that its "dispose" method is automatically invoked) once the try-catch-finally statement completes. When a try-catch-finally statement owns a resource, it is called a try-with-resource statement. In a try-with-resource statement, the catch and finally blocks can both be omitted.
Example
Let's copy a file from one place to another with a Stream that should be closed at the end.