Navigation bar
  Start Previous page
 102 of 206 
Next page End  

ZBasic Language Reference
94
ZX Microcontroller Family
overflowing the stack assigned to a task.  Heap corruption will also be the likely result of passing an
invalid value to System.Free().  The only values that may be safely passed to System.Free() are those
that have been returned by System.Alloc() but have not yet been passed to SystemFree().  As a special
case, passing the value zero to SystemFree() is benign.
The value Register.HeapEnd, described in this document, may be useful for monitoring the state of the
heap.  For additional information, see the descriptions of System.Alloc() and System.Free() in the ZBasic
System Library Reference manual.  Also, for native mode devices (e.g. the ZX-24n) the function
System.HeapHeadRoom() may be used to determine, at any time, the amount of unused space that
remains in the heap.  Moreover, for native mode devices the directive Option HeapSize can be used to
specify an upper limit on the size of the heap thereby preventing it from encroaching on the task stacks.
3.30 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()
Previous page Top Next page