Home > Net >  How to include a integer while throwing a failure exception in ocaml
How to include a integer while throwing a failure exception in ocaml

Time:06-12

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?

CodePudding user response:

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.

CodePudding user response:

If you wish to handle that exception, parsing that int out of the error message might be annoying.

Defining your own exception is something you should learn eventually when learning OCaml because it gives you the flexibility to pass any information you need in the exception. Here's a simple example:

exception Out_of_range of {
  range_start : int;
  range_end : int;
  received : int
}

Now, you can define your function as:

let f = function
| 1 -> "a"
| 2 -> "b"
| n -> raise (Out_of_range { range_start=1; range_end=2; received=n })

And when calling it:

let n = read_int () in
try
  f n
with
| Out_of_range {range_start=s; range_end=e; received=n} ->
  failwith (Format.sprintf "Argument should be between %d and %d but it was found to be %d" s e n)
  • Related