OCAML:遇到例外后,for循环应该忽略它并继续而不会抛弃我
因此,我有此代码:
let matrix = [|
[| true; true; true |];
[| false; false; false |];
[| false; true; true |];
[| true; false; false |]
|];;
for i = 0 to 10 do
for j = 0 to 10 do
try
if matrix.(i).(j) = true then
print_string "works"
with
| Invalid_argument "Index out of bounds" -> ();
done;
done;
我希望例外处理程序只能在没有打印作品的情况下继续循环,而是将我扔掉,但仍然给我一个例外。我在这里做错了什么?
So i have this code:
let matrix = [|
[| true; true; true |];
[| false; false; false |];
[| false; true; true |];
[| true; false; false |]
|];;
for i = 0 to 10 do
for j = 0 to 10 do
try
if matrix.(i).(j) = true then
print_string "works"
with
| Invalid_argument "Index out of bounds" -> ();
done;
done;
I want the exception handler to just continue the loop without printing works, instead it tosses me out and still gives me an exception. What am i doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当我对此进行编译时,我会得到:
好吧,您忽略了它,所以当我运行它时,我会得到:
“ index of Bounds”
与“ index of Bounds” 。您遇到了错误的例外。
When I compile this I get:
Well, you ignored this, so when I run it I get:
"Index out of bounds"
is not the same as"index out of bounds"
. You are catching the wrong exceptions.Goswin对匹配异常的情况不匹配是正确的。您的代码中也有不必要的分号,因为您没有将多个表达式链接在一起。
另请注意,在OCAML 4.02及以后,我们可以直接在
Match
中处理异常,因此可以将此代码表示为:如果您希望完全避免例外处理,则可以完全限制检查。
Goswin is correct about the case mismatch in matching the exception. You also have unnecessary semicolons in your code as you are not chaining multiple expressions together.
Also note that in OCaml 4.02 and later, we can handle exceptions directly in a
match
, so this code could be expressed as:If you wish to avoid the exception handling altogether, you could quite simply bounds check.
通常,
invalid_argument _
不应捕获或匹配异常。这些例外是作为编程错误,应在发生之前避免。在这种特定情况下,这意味着在使用索引之前检查索引是否在矩阵的边界内。
例如:
也可以定义一个矩阵访问操作员,该矩阵访问操作员返回选项类型,以便对循环外的界限进行分配:
In general,
Invalid_argument _
exceptions should not be catch nor matched.Those exceptions are meant as programming errors that should be avoided before they happen. In this specific case, this means checking that the indices are within the bound of the matrix before using them.
For instance:
It is also possible to define a matrix access operator that returns an option type in order to factorize the bound checking outside of the loop: