Like in C++, the
catch keywords are used to begin blocks of code where exceptions can be thrown and processed.
If an exception is thrown outside
catch, it will be uncaught and execution of the script to be aborted.
try: print 'Nothing thrown yet.' catch: print 'Skipped.'
Exceptions are thrown using a
throwcan be used inside a
catchcompound to rethrow the caught exception.
try throw "There was an error" catch print 'Exception caught' end
If the exception does not require any handling, one can use
pass as the catch block.
try: throw 'Problem!' catch: pass
The exception message can be assigned to a local variable so it can be accessed in the catch block.
try: throw "OMG!" catch Error, er print 'Caught:', er end
Caught: [Error] (in script) OMG!
catch blocks can be chained together to catch specific types of exceptions.
try throw 'This will be printed' catch NullError: print 'Got NullError' catch Error, er: print er catch: print 'Never here.'
Try/catch can be nested, and an exception thrown in an inner try block can be caught in an outer block.
try try try throw 'Deep.' catch BogusError end catch BogusError end try catch Error, er print 'Should *not* be caught here.' end catch Error, er print 'Got it:', er end
In this example, BogusError does not match the type of error thrown in scripts (a generic Error), so the catch blocks are skipped. The output is:
Got it: [Error] (in script) Deep.
An exception thrown in a function unwinds the call stack to find a matching catch block.
def erroneous() throw "Dropped the ball" end try print "Calling erroneous()" erroneous() try print 'This will be skipped!' catch print 'I am on the wrong catch level.' end catch print 'Fumbled it...' end
Native code may throw various kinds of exceptions that can then be caught in the script. In the example below, a
NullError gets thrown because the code tries to access a deleted object via an alias.
try record temp reference = temp del temp print reference catch NullError, er print 'Oh noes:', er end
ReadOnlyError is thrown when trying to change a
const SOME_CONSTANT = 3.1415 try SOME_CONSTANT = 3 catch ReadOnlyError, er print 'Cannot do it.', er end try const SOME_CONSTANT = 3 catch ReadOnlyError, er print 'Will not work either:', er end
Any type of native exception can be caught in a script.