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 TRYAlso 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.
ENDTRYandEND TRYare 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,ENDand aGOTOout of the block.ENDandGOTOare 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 aFUNCTIONit 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 fromCANCELTASK, with the messageBASIC task cancelled. The task then goes on until its next yield. PutRETHROWin the CATCH when the message isBASIC 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 ammoIn the manual : Errors