F#:自定义例外。有没有更好的方法来重载异常类型?

时间:2009-07-28 21:11:27

标签: exception f#

我有一个简单的自定义异常,如下所示,但我不喜欢使用Throw函数,而我真的不喜欢同时使用Throw和Throw2函数。有更优雅的方式吗?有没有办法在没有中间函数的情况下直接抛出MyError或Error?

#light

module Utilities.MyException

type MyError(code : int, msg : string) =
    member e.Msg  = msg
    member e.Code = code
    new (msg : string) = MyError(0, msg)

exception Error of MyError

let public Throw (msg : string) =
    let err = new MyError(msg)
    raise (Error err)

let public Throw2 (code : int) (msg : string) =
    let err = new MyError(code, msg)
    raise (Error err)

我正在使用它,如下所示,但我想使用其中一种不起作用的变体

Throw(System.String.Format("Could not parse boolean value '{0}'", key))

//The string isn't of the correct type for Error
//raise(Error(System.String.Format("Could not parse boolean value '{0}'", key)))

//MyError isn't compatible with System.Exception
//raise(MyError(System.String.Format("Could not parse boolean value '{0}'", key)))

3 个答案:

答案 0 :(得分:16)

只需忽略exception构造并定义异常类 - 即直接从System.Exception派生的异常类,就像在C#中一样:

type MyError(code : int, msg : string) =
    inherit Exception(msg)
    member e.Code = code
    new (msg : string) = MyError(0, msg)

raise(MyError("Foo"))
raise(MyError("Foo", 1))

请注意,我删除了Msg成员,因为Exception已经拥有等效的Message属性。

答案 1 :(得分:1)

我不清楚你究竟是在追求什么,但这对你有什么作用?

exception Error of int * string
let ErrorC(s) = Error(0,s)

let F() =
    try
        let key = true
        raise <| Error(42, System.String.Format("Could not parse '{0}'", key))
        raise <| ErrorC(System.String.Format("Could not parse '{0}'", key))
    with Error(code, msg) ->
        printfn "%d: %s" code msg

答案 2 :(得分:1)

如何将MyError重新定义为记录并使用记录语法记录错误,例如: -

type MyError =
    { Msg:  string;
      Code: int } 

exception Error of MyError

raise <| Error { Msg  = ( sprintf "Could not parse boolean value '%b'" key );
                 Code = code }