TRY

Statement

Syntax

Runs statements and catches the runtime error they raise. CATCH handles the error, FINALLY always runs at the end.

TRY
  <statements>
[CATCH [<name>[$]]
  <statements>]
[FINALLY
  <statements>]
ENDTRY
END TRY

Also written : CATCH, FINALLY, ENDTRY, END TRY

Parts

<statements>Any statements, including other TRY blocks.
<name>Optional catch variable. With $ it receives the message as a string. Without $ it receives a read-only record with the fields name, message, code and command. Without a name the error is dropped.

Good to know

  • A TRY needs a CATCH, a FINALLY or both: "TRY requires CATCH or FINALLY". The order is fixed: CATCH, then FINALLY. One CATCH at most.
  • ENDTRY and END TRY are the same. Each keyword stands on its own line: TRY: THROW "x" is not accepted.
  • FINALLY runs after a normal end, after an error, after EXITFUNCTION, RETURN, END and a GOTO out of the block. END and GOTO are not errors: CATCH never sees them.
  • Give the catch variable a name of its own. If the same name is declared or assigned elsewhere in the same scope, the program compiles but cannot start ("Identifier … has already been declared").
  • The catch variable stays readable after ENDTRY. Inside a FUNCTION it belongs to the function.
  • Compile errors are not caught: they stop the program before it runs. For catalogue commands, ErrorMode() decides whether a failure raises an error at all.
  • Inside a task, a TRY around a Wait(), Sync() or YieldTask() also catches the cancellation from CANCELTASK, with the message BASIC task cancelled. The task then goes on until its next yield. Put RETHROW in the CATCH when the message is BASIC task cancelled.

Example

TRY  THROW "out of ammo"CATCH problem$  Console("caught: " + problem$)   ' caught: out of ammoFINALLY  Console("cleanup")               ' cleanupENDTRYConsole("after: " + problem$)      ' after: out of ammo
In the manual : Errors

Commands that go with it