Can exception types be generic?

感情迁移 提交于 2019-12-07 05:22:19

问题


I've tried the following, which don't work.

exception MyError<'a> of 'a
exception 'a MyError of 'a

Do I have to use the long form:

type MyError<'a>(value) =
  inherit System.Exception()
  member this.Value : 'a = value

回答1:


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 := attributesoptexception 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


来源:https://stackoverflow.com/questions/6099027/can-exception-types-be-generic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!