pythongenius
pythongenius

Reputation: 3

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?

Upvotes: 0

Views: 187

Answers (2)

Chris
Chris

Reputation: 36611

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, if you want to raise a Failure with a formatted string:

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)

Upvotes: 3

axr
axr

Reputation: 416

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.

Upvotes: 5

Related Questions