You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OCaml抛出失败异常时如何在错误信息中嵌入输入整数参数

实现方法

核心问题是你原代码最后一个分支用的_是匿名通配符,不会将匹配到的入参绑定为可调用的变量,所以无法拿到实际传入的参数值。只需要两步修改即可:

  1. 把通配符_替换为自定义变量名,接住传入的非法参数
  2. 将整数类型的参数转为字符串,拼接/格式化到错误提示文本中

写法1:基础字符串拼接实现

直接用OCaml原生字符串拼接符^配合标准库的整数转字符串函数string_of_int即可,修改后完整代码:

let f = function
| 1 -> "a"
| 2 -> "b"
| x -> failwith ("Argument should be less than 3 and more than 0 but it was found to be " ^ string_of_int x)

传入非法值比如0、3时,抛出的异常信息会自动替换为对应数值,例如传入3时异常提示为:

Exception: Failure "Argument should be less than 3 and more than 0 but it was found to be 3".

写法2:格式化字符串实现

如果觉得手动拼接字符串繁琐,也可以用标准库Printf模块的sprintf函数做格式化输出,多参数插入时可读性更高:

let f = function
| 1 -> "a"
| 2 -> "b"
| x -> failwith (Printf.sprintf "Argument should be less than 3 and more than 0 but it was found to be %d" x)

运行效果和第一种写法完全一致。

内容的提问来源于stack exchange,提问作者pythongenius

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 17:45:37