2013-04-08 55 views
1

我们的教授要求我们做这在分配中:如何引发打印消息并返回值的异常?

If the threshold given is negative, you should print the message “Error: Negative Threshold” and return an empty list. To do this, define an exception called ThresholdOutOfRange, raise it if the threshold is negative, and handle the exception to achieve the proper behavior.

我不知道如何抛出一个异常,返回值,并打印错误消息。现在我的筹集异常代码是(刚刚与异常的重要位):

fun getnearbylist(center, threshold, ziplist) = 
    let 
     exception ThresholdOutOfRange; 
     fun test_threshold(threshold, zip, nil) =nil 
     | test_threshold(threshold, zip, ziplist as x::xs) = 
      if (threshold <0.0) then raise ThresholdOutOfRange 
(*  [...skipped a long unrelated middle bit. most important is just knowing 
       this function returns a string list...] *) 
      else x::test_threshold(threshold, zip, xs) 
    in 
     test_threshold(threshold, center, ziplist) 
     handle 
     ThresholdOutOfRange => [] 
    end 

因此,当引发异常我的代码将只返回一个空列表。鉴于异常必须具有与我所知道的函数相同的返回类型,我该如何才能返回空列表并输出错误消息?

回答

3

异常处理的结果类型必须与处理异常的表达式相同,也就是说,exp_1exp_2在下面的代码中必须具有相同的类型,就像“那么“和”其他“部分的if-表达式。

exp_1 handle pat => exp_2 

那么你正在寻找的是在exp_2部分做多件事情的方式,特别是一些具有打印信息的副作用。对于这样的事情,你可以使用序列。一个序列具有以下形式(注意括号)

(exp_1; ... ; exp_n) 

它本身就是一个表达式。这表现在以下

- (print "foo\n"; print "bar\n"; 42); 
foo 
bar 
val it = 42 : int 

从这一点我们可以看出,一个序列的最终结果是什么都exp_n评估为。

由于序列在松懈表达式经常使用的,它是允许写入以下(不含先前提到的括号)

let dec in exp_1 ; ... ; exp_n end 

奖金信息

序列实际上是一个派生形式(语法糖)的一系列案件。下面

(expr_1 ; ... ; exp_n ; exp) 

相当于

case expr_1 of _ => 
    case ... => 
    case exp_n of _ => exp 
+0

我相信这也被称为'副effecting' – eazar001 2013-04-09 23:55:12

1
  • 首先声明一个例外

    exception OutOfRangeException; 
    
  • 定义将引发异常的函数:

    fun someFunc x = 
        if x < 0 then 
        raise OutOfRangeException 
        else [1,2,3,4] (*return some list*) 
    
  • 最后,将通过打印消息并返回 和空单处理异常的函数:

fun someFunc_test x=  
    (someFunc x) handle OutOfRangeException => (print "exception"; []) 
+0

的异常不需要是全局的。它只是需要在代码的范围内处理它 – 2013-04-10 15:26:39

+0

@ Jesper.Reenberg我刚才提到它是一种很好的做法。 – tarrsalah 2013-04-11 21:28:50

+0

好吧,这不一定是好的做法。保持用户隐藏的异常可能有各种原因。例如,内部逻辑可以通过异常处理来实现,并且给予用户对异常的访问权限可能会使其失效。 一般而言,只要异常将被内部使用,就没有必要通过声明“全局”来污染环境。 – 2013-04-12 01:59:02