更具描述性的IndexOutOfRangeException

时间:2014-04-14 15:15:53

标签: f#

有没有办法获得更具描述性的Index-Out-Of-Range-Exceptions? 我想过像这样重写Item属性,但这不起作用:

type ``[]``<'T> with 
    override arr.Item        
        with get(i) = 
            if i<0 || i >= arr.Length then 
                failwithf "Index %d is Out of Range on Array(%d): %A" i arr.Length arr
            else 
                arr.[i]        
        and set (i: int) (value:'T) = 
            arr.[i] <- value

1 个答案:

答案 0 :(得分:2)

如果这仅用于调试,您可以配置VS以中断CLR异常(Debug&gt; Exceptions ...)以查看无效索引。否则,你可以这样做:

let idx = -1
try
    arr.[idx] <- x
with :? System.IndexOutOfRangeException ->
    failwithf "Index out of range: %d" idx

另一个选择是隐藏Array.get/Array.set

module Array =
    let get i (arr: 'T[]) =
        if i<0 || i >= arr.Length then 
            failwithf "Index %d is Out of Range on Array(%d): %A" i arr.Length arr
        else 
            arr.[i]