Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling multiple exception types in OCaml

Is the following possible?

try
  (* danger zone *)
with Not_found e -> 
  (* code to handle not found *)
with t -> 
  (* code to handle all other issues *)

If I type that into the toplevel, I get a syntax error on the second with. Perhaps there's some syntax I'm not aware of?

Is the preferred method to prepend another try to match each with?

like image 844
Nick Heiner Avatar asked Apr 24 '12 23:04

Nick Heiner


People also ask

Does OCaml have exceptions?

OCaml has exception handling to deal with exceptions, application-level errors, out-of-band data and the like. Exceptions are a very dynamic construct, but there is a third-party application that performs a static analysis of your use of exceptions and can find inconsistencies and errors at compile time!

What is Failwith in OCaml?

The simplest one is failwith , which could be defined as follows: let failwith msg = raise (Failure msg);; val failwith : string -> 'a = <fun> OCaml. There are several other useful functions for raising exceptions, which can be found in the API documentation for the Common and Exn modules in Base.

What does :: do in OCaml?

It is usually used if you have a function or value that is very similar to some other, but is in some way new or modified. Regarding the :: symbol - as already mentioned, it is used to create lists from a single element and a list ( 1::[2;3] creates a list [1;2;3] ).


1 Answers

The with part is a series of patterns, so you can write this as follows:

try
    (* dangerous code area *)
with
    | Not_found -> (* Not found handling code *)
    | t -> (* Handle other issues here *)
like image 72
Jeffrey Scofield Avatar answered Sep 21 '22 01:09

Jeffrey Scofield