Re: Readability of exception handling
Alan Baljeu <[email protected]>
| Newsgroups | gmane.comp.ai.prolog.swi |
|---|---|
| Message-ID | <[email protected]> |
>> Thanks for the reply, Alan. But that is one handler that catches >> only one exception. What about exception_1 with handler_1, >> exception_2 with handler_2,...? Does that have a flat structure or >> does it require nesting? > >There is indeed a lot to say about proper exception handling in Prolog. >Too often (me too), we see code such as > > catch(open(....), _, fail) > >which may fail because the file cannot be opened, but for zillions of >other reasons, such as wrong arguments to begin with or even some >resource error. If anyone is aware of a good story that describes >best practices here, please provide a pointer. > >Some issues: > > - What error terms to throw from user code? > - When to catch errors and when test that you won't get one? > - When to use setup_call_cleanup/3 (instead) > - How to deal with one specific exception? > - How to deal with a variety of exceptions that may happen? > - How and when to use print_message/2 > - How to use library(prolog_stack)? > >This could make a great tutorial! I'm happy to write some parts and >or comment! > > Cheers --- Jan My perspective is old-school C, and that exceptions are undesired complexity. There are two reasons to throw: a) When simple failure is insufficient information; you want to communicate the reason. b) When you want to short-circuit retries and escape up the stack. [Aside, if your program has frequent exceptions, do not code throw(my_exception(Info)), but rather throw_my_exception(Info) where throw_my_exception(ExceptionInfo) :- throw(my(ExceptionInfo)). Because: you can put all your exceptions together in one spot where they can be easily understood, standardized, and updated. ] There's really only two cases to catch: a) The code you're invoking can throw for known reasons, and you want to react. Try plan A, catch an exception, try plan B. (Plan B can be just fail.) b) Your code doesn't expect failure , and there's nothing to be done about it. In this case, you simply want the most informative message for the end user. Having specific exception types is irrelevant. This handler is at the level of user input/response. catch(Execute, AnyException, report(AnyException)). setup_call_cleanup is for whenever the call has side-effects that need undoing. I know nothing of print_message or prolog_stack. I do propose that no libraries should use such unless during debugging, or when fatal errors occur. -------------- next part -------------- HTML attachment scrubbed and removed