1
votes

I need to create a function that generates an exception in certain cases but I need it to generate a certain error using try catch. It uses functions :

let lookup (x,evn) =  match listAssoc(x,evn) with
|Some Int v ->Int v
| None -> raise (MLFailure "variable not found")
;;

let arithmetic (x,y,z) = match (x,y,z) with 
| (Int a, Int b, Plus)-> Int (a+b)
| (Int a, Int b,Minus) -> Int (a-b)
| (Int a, Int b, Mul)-> Int (a*b)
| (Int a, Int b, Div)-> Int (a/b)
;;

This is the function:

let errorlookup (x,evn) =  match listAssoc(x,evn) with
|Some Int v ->Int v
| None -> raise (Nano.MLFailure "variable not found %s" x)
;;
let rec eval (evn,e) = match e with
| Const a -> Int a
| Var x-> (lookup (x,evn) )
| Bin( expr1, Plus, expr2) ->   arithmetic(eval(evn,expr1),eval(evn,expr2),Plus)
|Bin( expr1, Minus,expr2) ->  arithmetic(eval(evn,expr1),eval(evn,expr2),Minus)
|Bin( expr1, Mul, expr2) ->   arithmetic(eval(evn,expr1),eval(evn,expr2),Mul)
| Bin( expr1, Div, expr2) ->  arithmetic(eval(evn,expr1),eval(evn,expr2),Div)

;;

I need to make sure that in the Var x case, when lookup result is None I need to print an Exception

eval (evn, Var "p");;
Exception: MLFailure "variable not bound: p".

eval evaluates an expression with a current environment ex.

let evn = [("z1",Int 0);("x",Int 1);("y",Int 2);("z",Int 3);("z1",Int 4)];;
val evn : (string * Nano.value) list =
  [("z1", Int 0); ("x", Int 1); ("y", Int 2); ("z", Int 3); ("z1", Int 4)]

I made the types for Bin and Val and Expr but those arent relevant to this.
I need to raise an exception based on the result of lookup but not raise the exception that is in lookup. Someone suggested using try catch but Im not sure how that would work for ocaml and this. this was the hint given by TA lookup should throw the following exception:

raise (MLFailure "not found")

Whereas eval should throw the following one:

eval (evn, Var "p");;

Exception: MLFailure "variable not bound: p".

It seems that you've to do exception handling here. You can use the

try with | ->

syntax to catch & handle exceptions inside eval.

1
What is the question? Have you tried Google or the OCaml manual? - antron

1 Answers

2
votes

It's not clear what you're asking. But I suspect your TA has told you what you need to know. You can read about the OCaml try ... with expression in Section 6.7 of the OCaml manual. This is the OCaml equivalent to try ... catch of some other languages.

If you want to catch a particular exception but let others propagate as usual, you just need to match the one you're interested in:

try
    <expression1>
with Not_found -> <expression2>

If you have complicated requirements, you can match several different exceptions, and after the match you can compute values and/or re-raise exceptions.

try
    <expression1>
with
| Not_found -> raise (MLFailure "abc")
| Divide_by_zero -> max_int
| _ -> raise (Invalid_argument "def")