From Exceptions (Syntax for throwing and catching), it says there are four useful exception keywords built into F#, with nullArg
throws a NullArgumentException
:
let f x =
if x then "ok"
else nullArg "paramName" "message"
If I'm writing modules for F# usage only, when should I raise a NullArgumentException
?
You shouldn't. Exceptions are bleh. Avoid them. Only use them when interfacing with external code that expects you to throw exceptions or doesn't give you another way to report errors.
Instead, if you're writing a function that may fail, make it return an "either/or" value - either result or an error. Along these lines:
type Result<'t, 'e> = Ok of 't | Error of 'e
let f x =
if x then Ok "ok"
else Error "boo!"
This way, the calling code can't "forget" to handle the error case: the compiler won't let it. This is a Good Thing.
Incidentally, F# 4.1 includes the Result
type in the box (and some useful utilities). Check out the example in that post.
Also of interest: here's a great series of articles and a presentation video on the subject.