Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can exception types be generic?

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
like image 538
Daniel Avatar asked May 23 '11 15:05

Daniel


People also ask

What is a generic exception?

It refers to exception class that is near the top of the exception class hierarchy. Note that an exception class cannot be a generic class ... in the Java sense of generic types. The JLS says: "Note that a subclass of Throwable cannot be generic (§8.1.2)." -

Can throwable class be generic?

We saw that a type variable can be used to specify the type of Throwable in the throws clause of a method. Perhaps ironically, however, we cannot use generics to create new types of exceptions. No generic subtypes of Throwable are allowed.

How do you catch generic exceptions?

Exception handling is used to handle the exceptions. We can use try catch block to protect the code. Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.

Can a generic class be a subclass of a non generic class?

Non-generic class can't extend generic class except of those generic classes which have already pre defined types as their type parameters.


1 Answers

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
like image 56
Tomas Petricek Avatar answered Sep 30 '22 02:09

Tomas Petricek