|
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"
|