Can exception types be generic?
I've tried the following, which don't work.
exception MyError<'a> of 'a
exception 'a MyError开发者_如何学C of 'a
Do I have to use the long form:
type MyError<'a>(value) =
inherit System.Exception()
member this.Value : 'a = value
According to the specification, you have to use the long form. I didn't find any explanation why that's the case, but the grammar for exception declarations looks like this (and maybe also hints why the behavior is as you described):
exception-defn := attributesopt exception union-type-case-data
union-type-case-data :=
ident (nullary union case)
ident of type * ... * type (n-ary union case)
ident : uncurried-sig (n-ary union case)
This is quite interesting, because it suggests that exception declarations are more like discriminated union cases than like types. I guess you can think of an exception declaration...
exception MyExn of int
...as a declaration adding new case to the standard System.Exception
type (if it was a discriminated union). In this case you wouldn't expect to be able to use a generic type parameter:
type System.Exception =
| ...
| MyExn of int
精彩评论