How can I handle errors in OCaml when using ncurses?

105 Views Asked by At

I'm learning OCaml, and I want to write a curses application. I'm very new to this language, and as I started writing the curses functions, I noticed that many of them have the type unit -> err. I can't find any good solutions for error handling in OCaml, and I'd appreciate some guidance.

My first solution to compile, was this:

open Curses

let () =
    let _win = initscr() in
    clear();
    let _err = noecho() in
    let _err = refresh() in

    endwin()

Basically, every time a function has a returning type 'err,' I assign an '_err' variable to it, but I don't think this is a good solution whatsoever. Is there any other solution to this? Can I approach it differently?

1

There are 1 best solutions below

0
Chris On

You are ignoring return values, which is definitely not a good habit to get into. Your code shown is equivalent to:

open Curses

let () =
  initscr();
  clear();
  noecho();
  refresh();
  endwin()

Except that that code will warn you that you're ignoring return values from functions by telling you that those functions do not return unit. You can overcome that by binding names to those return values, but then you'll get warnings about unused variables. You've gotten around this by prepending the names with underscores.

It's totally understandable to do this, but warnings from the compiler are important. They are hints that your code will compile, but may run into runtime issues instead. Suppressing them is depriving yourself of a valuable tool.

Handling the errors is the answer.

if not (noecho ()) then ...

What you choose to do is up to you. You could:

  • Raise an exception that can be handled by the caller. This exception can contain whatever meaningful data you want it to to enable the caller to handle the problem gracefully.
  • You could immediately try to rectify the issue and let the program proceed.
  • You can gracefully exit the program, preferably giving the user some useful feedback on what went wrong.