我有這個功能
let f = function
| 1 -> "a"
| 2 -> "b"
| _ -> failwith "Argument should be less than 3 and more than 0 but it was found to be x"
如何將x此處的值設定為等于函式的輸入?
uj5u.com熱心網友回復:
您可以使用sprintfPrintf 模塊中的標準庫函式。
| x -> failwith (Printf.sprintf "Argument should be ... but it was %d" x)
雖然,我建議您使用,invalid_arg而不是failwith因為您由于引數無效而引發例外。
查看OCaml 檔案的此頁面。
uj5u.com熱心網友回復:
如果您希望處理該例外,則從錯誤訊息中決議該 int 可能會很煩人。
在學習 OCaml 時,您最終應該學習定義自己的例外,因為它使您可以靈活地在例外中傳遞所需的任何資訊。這是一個簡單的例子:
exception Out_of_range of {
range_start : int;
range_end : int;
received : int
}
現在,您可以將函式定義為:
let f = function
| 1 -> "a"
| 2 -> "b"
| n -> raise (Out_of_range { range_start=1; range_end=2; received=n })
在呼叫它時,如果你想Failure用格式化的字串引發 a:
let n = read_int () in
try
f n
with
| Out_of_range {range_start=s; range_end=e; received=n} ->
failwith (Format.sprintf "Argument should be between %d and %d but it was found to be %d" s e n)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489144.html
上一篇:C#通過比較T和MyClasses在泛型方法中呼叫方法
下一篇:沒有捕捉到例外未定義的行為嗎?
