I have a simple custom exception defined like like the following but I don't like having to use the Throw function and I really don't like having both Throw and a Throw2 functions. Is there a more elegant way of doing this? Is there a way of throwing MyError or Error directly without the intermediate function?
#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)
I'm using it like the following but I'd like to use one of the variants that didn't work
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)))
Just ignore exception
construct and define the exception class - that is, one deriving from System.Exception
- directly, as in 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))
Note that I removed Msg
member, because Exception
has an equivalent Message
property already.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With