[Haskell-beginners] Generic exception available?

Antoine Latter aslatter at gmail.com
Sun May 15 22:09:32 CEST 2011


On Sun, May 15, 2011 at 1:23 PM, Daniel Fischer
<daniel.is.fischer at googlemail.com> wrote:
> On Sunday 15 May 2011 18:53:32, Christopher Howard wrote:
>> I have one spot in some code where I just want to raise an exception
>> that contains the message "Database is formatted incorrectly." Is there
>> some kind of generic way to throw that (like, e.g., in Ruby you just
>> call 'raise "exception message"'. In this case, I don't particularly
>> want to take the time to think about creating an Exception type or
>> finding a suitable one.
>
> Well, the simple thing would be calling
>
> error "Database is formatted incorrectly."
>
> which raises an exception of type ErrorCall.
> If you don't know what type of exception you should throw, ErrorCall might
> fit.
>
>>
>> (BTW: Is there a hierarchical list of standard Haskell Exception
>> instances somewhere?)
>
> There's no hierarchy, either a type is an instance of Exception or not,
> since there's no inheritance, there's no hierarchy (unless you count the
> universal Exception-wrapper SomeException, in which case we'd have a two-
> level hierarchy with that on top).
>
> The haddock docs for the Exception class in Control.Exception [to be found
> locally, on hackage, or on the ghc page] list the known instances.
>

The documentation for Control.Exception lists an example of how to
create an exception hierarchy:

http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Exception-Base.html#t:Exception

You can also create somehting like a hierarchy with ADTs:

> data MyException
>     = IOEx IOException
>     | Arith ArithException
>     | Assert AssertionFailed
>  deriving (Show, Typeable)

> instance Exception MyException where
>     toException (IOEx e)   = toException e
>     toException (Arith e)  = toException e
>     toException (Assert e) = toException e

>     fromException (fromException -> Just e) = Just (IOEx e)
>     fromException (fromException -> Just e) = Just (Arith e)
>     fromException (fromException -> Just e) = Just (Assert e)

You can even catch something as an 'IOException' even if it was thrown
as a 'MyException', or the other way around (it is the same with the
method described in the above link).

(Note that my example above uses ViewPatterns, a GHC extension. It can
be done without, but I am lazy.)

I'm not sure how useful the ADT approach is, but I think it is neat
what can be done with the extensible exceptions.

Antoine

> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>



More information about the Beginners mailing list