exceptionpattern-matchingocaml

How to include a integer while throwing a failure exception in OCaml


I have this function

let f = function
| 1 -> "a"
| 2 -> "b"
| _ -> failwith "Argument should be less than 3 and more than 0 but it was found to be x"

How do I set the value of x here equal to the function's input?


Solution

  • You can use the standard library function sprintf present in the Printf module.

    | x -> failwith (Printf.sprintf "Argument should be ... but it was %d" x)
    

    Although, I would recommend you to use invalid_arg instead of failwith since you are throwing the exception due to an invalid argument.

    Check out this page of the OCaml documentation.