【问题标题】:SML: How to check if exceptions have been raised?SML:如何检查是否引发了异常?
【发布时间】:2015-11-10 01:21:45
【问题描述】:

我正在编写一些关于在 SML 中读写文件的简单程序,并且我正在考虑跟踪文件是否成功打开/发生溢出等。如果在编译过程中引发任何异常,我希望函数返回 false 否则为 true。

这样的实现可行吗?如果是这样,怎么做?如果没有,还有其他解决方案吗?


我不确定我是否正确:

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;

但是,当文件的目录不存在时,这些解决方案都不会返回 []。为什么?

【问题讨论】:

  • "如果在编译过程中引发任何异常" 你的意思是在运行时?查看handle 声明。

标签: io sml


【解决方案1】:

是的,这是可行的:

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

现在,您可以调用logged f x 而不是调用f x 来获得相同的结果,但会记录任何异常。

【讨论】:

    猜你喜欢
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多