This next example uses parts of the previous example, but also opens a custom screen. Basically, it draws coloured lines and boxes in a big window opened on a 16 colour, high resolution screen.
MODULE 'intuition/intuition', 'graphics/view'
PROC main()
DEF sptr=NIL, wptr=NIL, i
sptr:=OpenS(640,200,4,V_HIRES,'Screen demo')
IF sptr
wptr:=OpenW(0,20,640,180,IDCMP_CLOSEWINDOW,
WFLG_CLOSEGADGET OR WFLG_ACTIVATE,
'Graphics demo window',sptr,$F,NIL)
IF wptr
TextF(20,20,'Hello World')
FOR i:=0 TO 15 /* Draw a line and box in each colour */
Line(20,30,620,30+(7*i),i)
Box(10+(40*i),140,30+(40*i),170,1)
Box(11+(40*i),141,29+(40*i),169,i)
ENDFOR
WHILE WaitIMessage(wptr)<>IDCMP_CLOSEWINDOW
ENDWHILE
WriteF('Program finished successfully\n')
ELSE
WriteF('Could not open window\n')
ENDIF
ELSE
WriteF('Could not open screen\n')
ENDIF
IF wptr THEN CloseW(wptr)
IF sptr THEN CloseS(sptr)
ENDPROC
As you can see, the error-checking IF blocks can make the program hard to read.
Here's the same example written with an exception handler:
MODULE 'intuition/intuition', 'graphics/view'
ENUM WIN=1, SCRN
RAISE WIN IF OpenW()=NIL,
SCRN IF OpenS()=NIL
PROC main() HANDLE
DEF sptr=NIL, wptr=NIL, i
sptr:=OpenS(640,200,4,V_HIRES,'Screen demo')
wptr:=OpenW(0,20,640,180,IDCMP_CLOSEWINDOW,
WFLG_CLOSEGADGET OR WFLG_ACTIVATE,
'Graphics demo window',sptr,$F,NIL)
TextF(20,20,'Hello World')
FOR i:=0 TO 15 /* Draw a line and box in each colour */
Line(20,30,620,30+(7*i),i)
Box(10+(40*i),140,30+(40*i),170,1)
Box(11+(40*i),141,29+(40*i),169,i)
ENDFOR
WHILE WaitIMessage(wptr)<>IDCMP_CLOSEWINDOW
ENDWHILE
EXCEPT DO
IF wptr THEN CloseW(wptr)
IF sptr THEN CloseS(sptr)
SELECT exception
CASE 0
WriteF('Program finished successfully\n')
CASE WIN
WriteF('Could not open window\n')
CASE SCRN
WriteF('Could not open screen\n')
ENDSELECT
ENDPROC
It's much easier to see what's going on here.
The real part of the program (the bit before the EXCEPT) is no longer cluttered with error checking, and it's easy to see what happens if an error occurs.
Notice that if the program successfully finishes it still has to close the screen and window properly, so it's often sensible to use EXCEPT DO to raise a zero exception and deal with all the tidying up in the handler.
Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.