Re: Error Handling
- Posted by Derek Parnell <ddparnell at bigpond.com> Mar 19, 2001
- 656 views
Jeff wrote: > I would rather use simple error return codes, like for open. I think, for > example, that this: > > integer fn > fn = open("thefile","w") > if fn = -1 then > -- do something > end if > -- a bunch of statements here > > Looks a lot better than: > > integer fn > fn = open("thefile","w") > -- A bunch of statements here > on error do > -- do something > I've written some programs using a flavour of Pick Basic. Many of its statements had the syntax of ... <KEYWORD> <PARAMS> ON ERROR <statements> ELSE <statements> END <KEYWORD> such as OPEN "thefile.e" FOR OUTPUT ON ERROR PRINT "File Failed to open" END OPEN I hated using it but after a while it was occasionally useful. But I digress. There are problems with error return codes. Firstly, it only applies to routines that return stuff - namely functions. Secondly, functions are usually designed to return something useful, which means that if they can return either an error code or a non-error value, the error code(s) must not be from the same set of values that non-error values belong to. This can often be designed, but not for everything. A function that is meant to return a string finds it hard to return an error code as well. Look at how awkward Euphoria's value() function is. A normal return value and an error code are from the same set so it must return a sequence. To do that it means you have to do an assignment first then a test for errors then another assignment! Not a good way to do things. Thirdly, some errors occur in expressions (eg Divide by zero), and there is nothing to return an error code when that happens. Imaging if we could do something like this .... ---------------- function value(sequence text) atom thenumber for i = 1 to length(text) do . . . if text[i] = badchar then raise #80001 with {i} end if if text[i] = anotherdot then raise #80002 with {i} end if end for return thenumber end function atom v sequence text v = value(text) if exception then if errno = #80002 then printf (1, "Extra dot in \"%s\" at position %d", {text, errdata[i]}) else printf (1, "Bad character at position %d in \"%s\"", {errdata[i], text}) end if end if ------------------- or even ... score = sqrt((sideA * sideB)) / Questions if exception then if errno = ZeroDivide then -- Ignore this result score = 0 else printf(1, "Fatal error #%d", {errno}) abort(1) end if end if and of course ... -- turn off exception handling without exceptions -- turn on exception handling with exceptions ------ Derek Parnell Melbourne, Australia "To finish a job quickly, go slower."