When to raise nullArg in F #

From Exception (syntax for throwing and trapping) , he 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 write modules just to use F #, when do I need to raise NullArgumentException

?

+3


source to share


2 answers


You should not. Exceptions are bleh. Avoid them. Use them only when interacting with external code that expects you to throw exceptions or give you no other way to report errors.

Instead, if you write a function that might fail, make it return either / or — either a result or an error. In these lines:

type Result<'t, 'e> = Ok of 't | Error of 'e

let f x =
   if x then Ok "ok"
   else Error "boo!"

      



Thus, the calling code cannot "forget" to handle the error case: the compiler will not allow this. This is a good thing.

By the way, F # 4.1 includes type Result

in field
(and some useful utilities). See an example in this post.

Also of interest: here is a whole series of articles and a presentation video on the subject.

+3


source


Even when you write code just to consume F #, I think there are perfectly valid use cases for exceptions in F # code.

If you have errors that you expect it is better to use type Result

. This includes reading data that might be malformed (because it comes from the user) or checking user inputs that might be wrong.

However, I think that exceptions are still useful for specifying exceptional cases. For nullArg

in particular, there aren't too many cases where you need to, because F # basically eliminates values null

, but you can still get them when you use the .NET type as an argument. If you have a function that takes IDictionary<string, string>

and you never expect it to be null

, it might be helpful 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"

      

Since it IDictionary

is a .NET type, F # does not guarantee that it will never be null

, and handling this case explicitly can give you more useful error information if you accidentally make a mistake in your code.

+4


source







All Articles