Io SML:如何检查是否引发了异常?
我正在编写一些关于在SML中读取和写入文件的简单程序,我正在考虑跟踪文件是否成功打开/是否发生溢出等。如果在编译过程中出现任何异常,我希望函数返回false或true 这样的实施可行吗?如果是,怎么做?若否,有否其他解决方法?Io SML:如何检查是否引发了异常?,io,sml,Io,Sml,我正在编写一些关于在SML中读取和写入文件的简单程序,我正在考虑跟踪文件是否成功打开/是否发生溢出等。如果在编译过程中出现任何异常,我希望函数返回false或true 这样的实施可行吗?如果是,怎么做?若否,有否其他解决方法? 我不确定我是否做得正确: fun getN(file) = let val input = TextIO.openIn file fun num(n) = case n of NONE => []
我不确定我是否做得正确:
fun getN(file) =
let
val input = TextIO.openIn file
fun num(n) =
case n of
NONE => []
| SOME(str) => str_to_num(str) @ num(TextIO.inputLine input)
in
if OS.FileSys.access(file, []) then
num(TextIO.inputLine input) before TextIO.closeIn input
else []
//OR
num(TextIO.inputLine input) before TextIO.closeIn input
handle Io => []
end;
但是,当文件目录不存在时,这两种解决方案都不会返回[]。为什么?是的,这是可行的:
fun wasExceptionRaised f x = (f x; false) handle e => true
这将执行f x
,放弃结果并返回false
,除非引发异常,在这种情况下,将处理、放弃异常e
,并返回true
。尽管您可能希望处理特定异常,而不是其他异常,例如在测试时:
val test_should_not_find_file =
(TextIO.openIn "non-existing-file"; false)
handle Io { cause = SysErr ("No such file or directory", _), ... } => true
| _ => false
如果只是在抛出异常时进行日志记录,则可以执行类似的操作:
structure YourLogger =
struct
fun logException e =
let val time = Date.toString (Date.fromTimeLocal (Time.now ()))
val msg = "On " ^ time ^ " an error occurred: "
^ General.exnName e ^ ".\n"
^ General.exnMessage e
in appendFile "myLog.txt" msg end
fun logged f x = f x handle e => (logException e; raise e)
end
现在,您可以调用
f x
,而不是调用logged f x
,以获得相同的结果,但其中记录了任何异常。“如果在编译期间引发任何异常”是指在运行时?查看句柄
语句。