Error handling example

Suppose a user needs direct access to the data within a database channel. The following function does all the work in opening and closing the file, allocating sufficient memory, and reading the file. The function could fail for a variety of reasons, such as the file doesn't exist, the specified channel does not exist, or failure to allocate sufficient memory. To handle possible failures, the function uses a TRY block to do the work, and executes clean-up code in the corresponding ONERROR block.

! function to read an entire database channel into
! a float buffer, and return a pointer to that buffer.
DEFINE FUNCTION ReadChannel( filename, channel )
  TRY
    local integer fd, error, i
    local float ptr buffer
    fd = DBOpen( filename, "r" )
    if ( fd = 0 ) then
      call EASIError( 700 )
    endif
    buffer = EAlloc( float, DBPixels(fd) * DBLines(fd) )
    for i = 0 to DBLines(fd)-1
       call DBReadLine( fd, channel, i, 0, DBPixels(fd), \
       buffer + i*DBPixels(fd) )
    endfor
    call DBClose( fd )
    return( buffer )
  ONERROR
    if ( fd != 0 ) then
       call DBClose( fd )
    endif
    if ( buffer != NULL ) then
       call EFree( buffer )
    endif
    call ReCastEASIError()
  ENDONERROR
ENDDEFINE

The ONERROR block ensures the file is closed, and that allocated memory is freed when any errors occur anywhere during the execution of the TRY block. The error is then re-cast at the end of the onerror block, so that it can be detected by a higher level error handler. Since the DBOpen() function returns zero if an error occurs instead of causing an EASI error, the EASIError() intrinsic is used directly to trigger an error so that the error handling code can immediately take over.

The ReadChannel() function could then be used as follows, for example, to compute the average value within an image channel:

local float ptr buffer
local integer i
local double sum, average
try
  buffer = ReadChannel( "irvine.pix", 1 )
  for i = 1 to f$len( buffer )
    sum = sum + buffer[i]
  endfor
  average = sum / f$len( buffer )
  call EFree( buffer )
onerror
  print "The following error occured:"
  print GetLastErrorMessage()
endonerror

Note that using EASI to perform a large computation such as in the above example is not particularly efficient, and could take a relatively long time for even moderately sized images!

© PCI Geomatics Enterprises, Inc.®, 2026. All rights reserved.