Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a custom exception in Haskell?

The Control.Exception documentation says I can do the following to create my own exception:

 data MyException = ThisException | ThatException
     deriving (Show, Typeable)

 instance Exception MyException

If I paste this into a file and compile (after importing Control.Exception and Data.Typeable), I get:

exp.hs:6:20:
    Can't make a derived instance of `Typeable MyException'
      (You need -XDeriveDataTypeable to derive an instance for this class)
    In the data type declaration for `MyException'

Must I turn on this extension in order to have user-defined exceptions? If not, someone please provide an example. Thanks.

like image 659
me2 Avatar asked Feb 16 '10 04:02

me2


People also ask

Does Haskell have exceptions?

There are three different ways exceptions can be thrown in Haskell: Synchronously thrown: an exception is generated from IO code and thrown inside a single thread. Asynchronously thrown: an exception is thrown from one thread to another thread to cause it to terminate early.

How do you use try in Haskell?

try :: Exception e => IO a -> IO (Either e a) try takes an IO action to run, and returns an Either . If the computation succeeded, the result is given wrapped in a Right constructor. (Think right as opposed to wrong). If the action threw an exception of the specified type, it is returned in a Left constructor.


1 Answers

Yes, you need to turn on that extension. It's not a good idea to try to write the Typeable instance by hand because it has some ties to the internals of GHC.

like image 171
GS - Apologise to Monica Avatar answered Oct 23 '22 05:10

GS - Apologise to Monica