ZBasic Language Reference
99
ZBasic Microcontrollers
3.32 Exception Handling
ZBasic implements a simple but effective form of exception handling using a concept borrowed from the
C language. In the normal execution of a program, the call-return process is orderly and rigid. A routine
can only return directly to the routine that called it. This forms a natural hierarchy that works well in most
cases. However, it is sometimes the case that your program will detect a set of circumstances that
preclude normal operation. In such cases, it is useful to be able to discard the normal call-return
hierarchy and return directly to some distant caller, sending back a value to indicate the nature of the
conditions that required the exceptional action.
The simple example below shows how to utilize the exception handling mechanism.
Dim jmpBuf1(1 to System.JumpBufSize) as Byte
Sub Main()
debug.print "start test"
' initialize the jump buffer
Select Case SetJmp(jmpBuf1)
Case 0
' control came back from SetJmp()
debug.print "calling foo()"
Call foo()
debug.print "normal return from foo()"
Case 1
' control came back from LongJmp()
debug.print "SetJmp() returned 1 via LongJmp()"
End Select
debug.print "end test"
End Sub
Sub foo()
debug.print "in foo()"
Call bar()
debug.print "returning from foo()"
End Sub
Sub bar()
debug.print "in bar()"
Call LongJmp(jmpBuf1, 1)
debug.print "returning from bar()"
End Sub
Running this program will result in the following debug output:
start test
calling foo()
in foo()
in bar()
SetJmp() returned 1 via LongJmp()
end test
Note that the last lines of neither foo() nor bar() were executed nor was the line after the call to
foo() in Main(). If you comment out the call to LongJmp() in bar(), the program will produce the
following debug output:
start test
calling foo()
in foo()
|