I want my exception to carry data of variable type. Something like

exception Ex1<'t> of 't

let f<'t> (x:'t) = throw (Ex1 x)

But this does not seem possible.

Correct. Polymorphic exceptions would break the type system so they are prohibited.

So then I thought, I'll put it in a polymorphic module. Something like:

module m<'t> =

exception Ex1 of 't

let f (x:'t) = throw (Ex1 x)

But polymorphic modules does not seem possible either.

Correct.

How do I publish a polymorphic library with exceptions that carry polymorphic data?

In essence, you cannot. The most obvious workaround I can think of is to write your code in CPS and present an exceptional continuation to the user that provides a polymorphic value representing the exception. Another solution is to box the value that you're passing in the exception. Depending on the specifics of your problem, you may also be able to return a variant that is either the normal or an exceptional value where the variant is parameterized over the type of exceptional value.

By on 3/28/2009 7:35 PM ()

This isn't a real answer, but you can create an exception object via the OO features:

1
2
3
4
5
6
7
8
9
10
11
12
13
 

type Ex1<'a>(a:'a) =
    inherit Exception()
    member x.SomeData = a 

try
    let f x = raise (Ex1(x))
    f "hi"
with
    _ -> ()

The problem is that matching doesn't work.

By on 3/26/2009 2:17 AM ()

Well, you can match them if you know what type to expect:

1
2
3
4
5
try
    let f x = raise (Ex1(x))
    f "hi"
with
    | :? Ex1<string> as e -> e.SomeData

And if you don't, you can use some ugly reflection instead to get a roughly similar effect:

1
2
3
4
5
6
try
    let f x = raise (Ex1(x))
    f "hi"
with
    | e when (e.GetType().IsGenericType && e.GetType().GetGenericTypeDefinition() = typedefof<Ex1<_>>) ->
          "Caught polymorphic exception"
By on 3/26/2009 7:53 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper