Exceptions: The invalidArg Function (F#)

The invalidArg function generates an argument exception.

invalidArg parameter-name error-message-string

Remarks

The parameter-name in the previous syntax is a string with the name of the parameter whose argument was invalid. The error-message-string is a literal string or a value of type string. It becomes the Message property of the exception object.

The exception generated by invalidArg is a System.ArgumentException exception. The following code illustrates the use of invalidArg to throw an exception.

let months = [| "January"; "February"; "March"; "April";
                "May"; "June"; "July"; "August"; "September";
                "October"; "November"; "December" |]

let lookupMonth month =
   if (month > 12 || month < 1)
     then invalidArg "month" (sprintf "Value passed in was %d." month)
   months.[month - 1]

printfn "%s" (lookupMonth 12)
printfn "%s" (lookupMonth 1)
printfn "%s" (lookupMonth 13)

The output is the following, followed by a stack trace (not shown).

December
January
System.ArgumentException: Month parameter out of range.

See Also

Reference

Exception Types (F#)

Exceptions: The try...with Expression (F#)

Exceptions: The try...finally Expression (F#)

Exceptions: the raise Function (F#)

Exceptions: The failwith Function (F#)

Other Resources

Exception Handling (F#)