User Tools

Site Tools


This is an old revision of the document!


Try and catch

Like in C++, the try and catch keywords are used to begin compounds of code where exceptions can be thrown and processed.

If an exception is thrown outside try/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 throw statement.

  • When given one argument, a new exception is thrown with the argument converted to a text string. The argument should be used for instance for error messages.
  • Without arguments, throw can be used inside a catch compound to rethrow the caught exception.
    throw "There was an error"
    print 'Exception caught'

If the exception does not require any handling, one can use pass as the catch compound.

try: throw 'Problem!'
catch: pass

The exception message can be assigned to a local variable so it can be accessed in the catch compound.

try: throw "OMG!"
catch Error, er
    print 'Caught:', er


Caught: [Error] (in script) OMG!

Try/catch can be nested, and an exception thrown in an inner try compound can be caught in an outer compound.

            throw 'Deep.'
        catch BogusError
    catch BogusError
catch Error, er
    print 'Got it:', er

In this example, BogusError does not match the type of error thrown in scripts (a generic Error), so the catch compounds are skipped. The output is:

Got it: [Error] (in script) Deep.
  • Nesting try/catch statements.
  • Throwing exception in a function.
  • Catching a specific type of exception.
  • Multiple catch statements.
  • Exception thrown in another module.
  • Exception thrown in recursive call.
  • Exception from trying to change a read-only variable.
script/walkthrough/exceptions.1574274609.txt.gz · Last modified: 2019-11-20 20:30 by skyjake