Browse thread
Preferred use of Invalid_argument and Failure
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Xavier Leroy <Xavier.Leroy@i...> |
| Subject: | Re: [Caml-list] Preferred use of Invalid_argument and Failure |
> Let's quote the manual (release 3.09): > > exception Invalid_argument of string > > Exception raised by library functions to signal that the given > arguments do not make sense. > > exception Failure of string > > Exception raised by library functions to signal that they are > undefined on the given arguments. > > > It seems to me that Invalid_argument is a sort of specialisation of > Failure. The convention that the standard library tries to follow is this. Invalid_argument is very much like a failed assertion: it indicates that something is wrong in the program itself, i.e. negative character positions in string functions. Most programs will not catch Invalid_argument, treating as a fatal error. Others will catch it, but only to enter a piece of generic "recover from unexpected error" code. Failure, on the other hand, signals errors that can happen in normal runs of the code. For instance, you're converting a user-provided string to a number, and the string does not represent a number. It is expected that the client code catches Failure and recovers gracefully, e.g. by asking for the number again, or producing a precise "syntax error" message. I recommend the use of Invalid_argument to report "should never happen" conditions at the boundary between library functions and user code. On the other hand, the "Failure" exception is a bit of a legacy from earlier designs (Caml Light and even the original LeLisp-based Caml), and often is not the best way to report "normal error" conditions: instead, you could consider defining your own exceptions as Alain suggested, or even have your functions return "option" types instead of raising exceptions. Hope this helps, - Xavier Leroy