异常模式必须位于匹配案例的顶层

Exception patterns must be at the top level of a match case

编译:

let inputFile = open_in("test.txt");
let line = try(input_line(inputFile)) {
| End_of_file => "end of file"
};
print_endline(line);

但不是这个:

let inputFile = open_in("test.txt");
try(input_line(inputFile)) {
| line => print_endline(line)
| exception End_of_file => print_endline("end of file")
};

对于后者我得到一个错误:"Exception patterns must be at the top level of a match case"

我很困惑,因为它看起来与文档中的模式完全相同 (https://reasonml.github.io/docs/en/exception.html)

let theItem = "a";
let myItems = ["b","a","c"];
switch (List.find((i) => i === theItem, myItems)) {
| item => print_endline(item)
| exception Not_found => print_endline("No such item found!")
};

编译无误。

更改匹配项的顺序或删除 "exception" 关键字不会更改错误。

这个错误是什么意思?我不确定 "top level" 是什么意思。

try 与异常处理一起使用,类似于 JavaScript 中的 try/catch。在您的情况下,您想进行模式匹配并捕获异常(reasonml 允许),因此您可以只使用 switch.

let inputFile = open_in("test.txt");
switch(input_line(inputFile)) {
| line => print_endline(line) 
| exception End_of_file => print_endline("end of file")
};