How to do Try-Finally in ReScript?

66 Views Asked by At

According to ReScript's documentation, try-catch blocks cannot have a finally clause.

My question is twofold:

Firstly, what on Earth possessed them? What was the motivation? How does removing this functionality help us as developers? After all, the entire point of building yet another wrapper around JS is to provide a better experience, yes?

And secondly, what do they expect us to use instead? Sure, if we're writing the function that throws, we can eschew exceptions entirely and return an option; but if we're calling a JS function (or an RS function written by someone else) we don't have that...well...option.

Short of duplicating the cleanup code in all possible code paths, I have to admit I'm at a loss.

1

There are 1 best solutions below

4
glennsl On

ReScript is not a language built on top of JavaScript. It's a language built on top of OCaml and compiles to JavaScript.

The reason it does not exist in OCaml is probably because it was deemed unnecessary initially, given a minimalist approach, and exceptions later deemed non-idiomatic with the existence of option and result.

It can easily be user-defined as a simple function:

let protect = (~finally, f) => {
  let result = try f() catch {
  | exn =>
    finally()
    raise(exn)
  }
  finally()
  result
}