Prev: Modules
Exceptions
An exception is the result of an attempt to perform an invalid operation. By default, exceptions result in a popup window showing the exception message text.
An exception thrown by m will always have the following format:
| | |
ExceptionFormat := tag ':' message
|
|
The tag is always an (english) identifier, and independent of the language chosen when installing m. The message however depends on the language. See section * () for a list of m exception tags.
Catching Exceptions
Exceptions can also be handled ("catched") in m itself:
try
// code potentially throwing exceptions
catch exc by
// code handling the exception exc
end
|
The result of such a try block is the following:
- If the code between try and catch does not throw any exception, the code between catch and end will never be executed.
- If the code between try and catch does throw an exception, the exception will be assigned to the variable denoted by catch and the following code will be executed.
In the following example,
a[1] tries to access an non-existing element.
m throws an
ExcIndexOutOfRange, which is catched and simply printed:
try
a=[12];
print a[1]
catch e by
print "Got", e
end
→ Got ExcIndexOutOfRange: Array index is out of range
|
Try blocks can be nested to any depth (as long as the required memory is available).
| | |
TryStatement := try StatementList
catch ExceptionVariable by StatementList end .
ExceptionVariable := Identifier .
|
|
Throwing Exceptions
Exceptions can also be thrown explicitly in the code:
This will evaluate expression and use it as exception message. In the following example, an exception with the message "state.dat does not exist" will be thrown if this file does not exist.
if not files.exists("state.dat") then
throw "state.dat does not exist"
end
|
| | |
ThrowStatement := throw Expression .
|
|
Next: Object Oriented Programming© 2004-2011 airbit AG, CH-8008 Zürich
Document AB-M-REF-887