所以我有這個代碼:
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;
我希望例外處理程式在不列印的情況下繼續回圈,而是把我扔出去,仍然給我一個例外。我在這里做錯了什么?
uj5u.com熱心網友回復:
當我編譯這個時,我得到:
Warning 52: Code should not depend on the actual values of
this constructor's arguments. They are only for information
and may change in future versions. (See manual section 9.5)
好吧,你忽略了這一點,所以當我運行它時,我得到:
worksworksworksException: Invalid_argument "index out of bounds".
"Index out of bounds"
不一樣"index out of bounds"
。您正在捕獲錯誤的例外。
uj5u.com熱心網友回復:
Goswin 關于匹配例外的大小寫不匹配是正確的。您的代碼中還有不必要的分號,因為您沒有將多個運算式鏈接在一起。
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 _ -> ()
done
done
另請注意,在 OCaml 4.02 及更高版本中,我們可以直接在 a 中處理例外match
,因此這段代碼可以表示為:
for i = 0 to 10 do
for j = 0 to 10 do
match matrix.(i).(j) with
| true -> print_string "works"
| false | exception Invalid_argument _ -> ()
done
done
如果您希望完全避免例外處理,您可以非常簡單地進行邊界檢查。
let height = Array.length matrix in
for i = 0 to (min 10 (height - 1)) do
let width = Array.length matrix.(i) in
for j = 0 to (min 10 (width - 1)) do
if matrix.(i).(j) then
print_string "works"
done
done
uj5u.com熱心網友回復:
通常, Invalid_argument _
不應捕獲或匹配例外。這些例外意味著在發生之前應該避免的編程錯誤。在這種特定情況下,這意味著在使用索引之前檢查索引是否在矩陣的范圍內。
例如:
for i = 0 to 10 do
for j = 0 to 10 do
if i < Array.length matrix && i >= 0
&& j < Array.length matrix.(i) && j >= 0
&& a.(i).(j)
then print_string "works"
done
done
也可以定義一個回傳選項型別的矩陣訪問運算子,以便在回圈外分解邊界檢查:
let (.?()) a (i,j) =
if i < Array.length a && i >= 0
&& j < Array.length a.(i) && j >=0
then
Some (Array.unsafe_get (Array.unsafe_get a i) j)
else None
for i = 0 to 10 do
for j = 0 to 10 do
match matrix.?(i,j) with
| None | Some false -> ()
| Some true -> print_string "work"
done
done
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/473230.html
上一篇:在拋出此例外的方法中拋出例外