Exceptions: The invalidArg Function
The invalidArg
function generates an argument exception.
Syntax
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 (nameof 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: Value passed in was 13. (Parameter 'month')
See also
Samarbejd med os på GitHub
Kilden til dette indhold kan findes på GitHub, hvor du også kan oprette og gennemse problemer og pullanmodninger. Du kan få flere oplysninger i vores vejledning til bidragydere.