OCaml By Examples

errors

main.ml

open Core
Similarly to the `'a option` variant type, the `('a, 'b) result` variant type can be used to return some value of some type, or some error of some type (here, a `string`).
let can_error i =
  if i >= 0 then 
    Ok i
  else
    Error "you gave me a negative int"

let () =
  let args = Sys.get_argv () in 
  match args.(1) with 
  | "result" -> (
`match` can be used to sort through the tags of the `result` variant type.
    let res = can_error (-1) in
    match res with 
    | Ok i -> printf "success: %d\n" i 
    | Error s -> printf "error: %s\n" s
  )
`failwith` can be used to raise an exception.
  | "failwith" -> failwith "some error message"
  | "exn" -> 
Exceptions can be crafted and raised manually by declaring custom `'a exn` types (here, `Foo`) and throwing them using the `raise` function.
    let exception Foo of string in
    raise (Foo "some other error message")
  | _ -> print_endline "argument not recognized"
Note that any code that comes after a raised exception will not get executed. Also see https://github.com/janestreet/ppx_expect
let () =
  print_endline "this might not get executed"

console

$ dune exec ./main.exe -- result
error: you gave me a negative int
this might not get executed

$ dune exec ./main.exe 
Uncaught exception:
  
  (Invalid_argument "index out of bounds")

$ dune exe ./main.exe -- failwith
Uncaught exception:
  
  (Failure "some error message")

Raised at Stdlib.failwith in file "stdlib.ml", line 29, characters 17-33
Called from Dune__exe__Main in file "book/chapters/errors/main.ml", line 7, characters 18-47

$ dune exe ./main.exe -- exn
Uncaught exception:
  
  Foo("some other error message")

Raised at Dune__exe__Main in file "book/chapters/errors/main.ml", line 21, characters 4-42

$ dune exe ./main.exe -- some_arg
argument not recognized
next: bits