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?
Even when you are writing code just for F# consumption, I think there are perfectly valid cases for using exceptions in F# code.
If you have errors that you expect, then it might be better to use the Result type. This include reading data that might be ill-formed (because it comes from the user) or validating user inputs that might be incorrect.
However, I think exceptions are still useful for indicating exceptional cases. For nullArg specifically, there are not many cases when you'd need it because F# mostly eliminates null values, but you can still get one when you are taking a .NET type as an argument. If you have a function taking an IDictionary<string, string> and you never expect this to be null, it might be useful to write:
let lookupName (dict:IDictionary<string, string>) =
if dict = null then nullArg "dict" "lookupName expects a valid dictionary!"
if dict.ContainsKey "name" then dict.["name"] else "anonymous"
As IDictionary is a .NET type, F# does not make sure that it is never null and handling the case explicitly might give you more useful error information in case you do accidentally something wrong in your code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With