chessguy
chessguy

Reputation: 165

Handle Exception: Failure "nth"

In Python, it is quite simple to manage certain error with unit tests. For instance, to verify if a list is emptied or not, I can use assert test != []

Suppose the empty list let test = [];;

try
 ignore (nth test 0)
with
 Not_found -> print_string("Erreur!");;
   Exception: Failure "nth"

I need to raise an error - print_string ("Erreur!") when I encounter Exception: Failure "nth". So far the try/with did not really help me. In Ocaml, is there a workaround to raise the error and print something when I get Exception: Failure "nth"?

Upvotes: 0

Views: 1191

Answers (2)

ivg
ivg

Reputation: 35270

In Python, it is quite simple to manage certain error, with unit tests. For instance, to verify if a list is emptied or not, I can use assert test != []

You can do exactly the same (modulo syntax) in OCaml

let require_non_empty xs = 
  assert (xs <> [])

If you would like to hush an exception and raise in its absence, you can use the match construction, here is how your example could be expressed in OCaml,

let require_empty xs = match List.nth xs 0 with
  | exception _ -> ()
  | _ -> failwith "the list shall be empty"

In addition, testing frameworks, e.g., OUnit2, provide special functions such as assert_raises for these specific cases.

Upvotes: 1

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

You seem to be asking whether you can test for specific exceptions. Yes. The exception handling part after with is a list of patterns similar to the match expression.

try
    ignore (List.nth [] 0)
with
| Not_found -> ()
| Failure s -> print_string ("Erreur: " ^ s)
| _ -> ()

(It probably isn't wise to depend on the exact string supplied as the argument to Failure. The compiler, in fact, warns you not to do this.)

OCaml also has an asssert expression:

# let list = [] in assert (List.length list > 0);;
Exception: Assert_failure ("//toplevel//", 1, 17).

You can use try/with to handle the resulting exception, of course. The argument to Assert_failure gives the filename, line number, and character number on the line.

Upvotes: 1

Related Questions